diff --git a/python/user_packages/Python313/site-packages/__pycache__/brotli.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/brotli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faf5dce9d5ccba24814851b088ffb0a32a94da26 Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/brotli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/jsonpatch.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/jsonpatch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ef7b043a3eb3b828a5ed4c100a636dad7ad2ef Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/jsonpatch.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/jsonpointer.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/jsonpointer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96ac911b820ad5ba857dc6364d2f6103f03a3b05 Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/jsonpointer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/kaitaistruct.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/kaitaistruct.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35742d217fb17c2985aeafdc789901ae8e75f8d5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/kaitaistruct.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/mypy_extensions.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/mypy_extensions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df67a8288ba0c46b522925a974da7262414a5fc Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/mypy_extensions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/six.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/six.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17e858d1407f0acbc3d46b5fb7fe8a8ec796b4ba Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/six.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/socks.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/socks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0153c962ce2fe044a48520cb7a218d1cfeb20e3d Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/socks.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/sockshandler.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/sockshandler.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116a8e48791e6a4f1f07bffb74340c45788896b9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/sockshandler.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/__pycache__/typing_inspect.cpython-313.pyc b/python/user_packages/Python313/site-packages/__pycache__/typing_inspect.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a74e2db179379a00f84335ea1f889cf72a6295 Binary files /dev/null and b/python/user_packages/Python313/site-packages/__pycache__/typing_inspect.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__init__.py b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..808cf016d5cc9caaaa827540c5d367511276d75b --- /dev/null +++ b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__init__.py @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: MIT + +from ._ffi import ffi, lib + + +__all__ = ["ffi", "lib"] diff --git a/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a61bce12e7375ee36f4ef3da9e6c7d8684c12158 Binary files /dev/null and b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/_ffi_build.cpython-313.pyc b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/_ffi_build.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee2cd566eb3ecc7f45fff6efce3d236beaf2d467 Binary files /dev/null and b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/_ffi_build.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi.pyd b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi.pyd new file mode 100644 index 0000000000000000000000000000000000000000..95b09aa1e2de54c6a59e0142625f8de7b6e322e1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi.pyd differ diff --git a/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi_build.py b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi_build.py new file mode 100644 index 0000000000000000000000000000000000000000..ca30686b2f047cbcf013a99135ebd748fc08774b --- /dev/null +++ b/python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi_build.py @@ -0,0 +1,233 @@ +# SPDX-License-Identifier: MIT + +import os +import platform +import sysconfig + +from pathlib import Path + +from cffi import FFI + + +use_system_argon2 = os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1" +use_sse2 = os.environ.get("ARGON2_CFFI_USE_SSE2", None) +windows = platform.system() == "Windows" +# Free-threaded CPython doesn't support limited API. +limited_api = not sysconfig.get_config_var("Py_GIL_DISABLED") + + +# Try to detect cross-compilation. +def _get_target_platform(arch_flags, default): + flags = [f for f in arch_flags.split(" ") if f.strip() != ""] + try: + pos = flags.index("-arch") + + return flags[pos + 1].lower() + except ValueError: + pass + + return default + + +target_platform = _get_target_platform( + os.environ.get("ARCHFLAGS", ""), platform.machine() +) + + +if use_sse2 == "1": + optimized = True +elif use_sse2 == "0": + optimized = False +else: + # Optimized version requires SSE2 extensions. They have been around since + # 2001 so we try to compile it on every recent-ish x86. + optimized = target_platform in ("i686", "x86", "x86_64", "AMD64") + + +ffi = FFI() + +if use_system_argon2: + ffi.set_source( + "_ffi", + "#include ", + libraries=["argon2"], + py_limited_api=limited_api, + ) +else: + lib_base = Path("extras") / "libargon2" / "src" + ffi.set_source( + "_ffi", + "#include ", + extra_compile_args=["-msse2"] if (optimized and not windows) else None, + include_dirs=[str(Path("extras", "libargon2", "include"))], + py_limited_api=limited_api, + sources=[ + str(lib_base / path) + for path in [ + "argon2.c", + Path("blake2") / "blake2b.c", + "core.c", + "encoding.c", + "opt.c" if optimized else "ref.c", + "thread.c", + ] + ], + ) + + +ffi.cdef( + """\ +typedef enum Argon2_type { + Argon2_d = ..., + Argon2_i = ..., + Argon2_id = ..., +} argon2_type; +typedef enum Argon2_version { + ARGON2_VERSION_10 = ..., + ARGON2_VERSION_13 = ..., + ARGON2_VERSION_NUMBER = ... +} argon2_version; + +int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, + const uint32_t parallelism, const void *pwd, + const size_t pwdlen, const void *salt, + const size_t saltlen, void *hash, + const size_t hashlen, char *encoded, + const size_t encodedlen, argon2_type type, + const uint32_t version); + +int argon2_verify(const char *encoded, const void *pwd, + const size_t pwdlen, argon2_type type); + +const char *argon2_error_message(int error_code); + + +typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate); +typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate); + +typedef struct Argon2_Context { + uint8_t *out; /* output array */ + uint32_t outlen; /* digest length */ + + uint8_t *pwd; /* password array */ + uint32_t pwdlen; /* password length */ + + uint8_t *salt; /* salt array */ + uint32_t saltlen; /* salt length */ + + uint8_t *secret; /* key array */ + uint32_t secretlen; /* key length */ + + uint8_t *ad; /* associated data array */ + uint32_t adlen; /* associated data length */ + + uint32_t t_cost; /* number of passes */ + uint32_t m_cost; /* amount of memory requested (KB) */ + uint32_t lanes; /* number of lanes */ + uint32_t threads; /* maximum number of threads */ + + uint32_t version; /* version number */ + + allocate_fptr allocate_cbk; /* pointer to memory allocator */ + deallocate_fptr free_cbk; /* pointer to memory deallocator */ + + uint32_t flags; /* array of bool options */ +} argon2_context; + +int argon2_ctx(argon2_context *context, argon2_type type); + +/* Error codes */ +typedef enum Argon2_ErrorCodes { + ARGON2_OK = ..., + + ARGON2_OUTPUT_PTR_NULL = ..., + + ARGON2_OUTPUT_TOO_SHORT = ..., + ARGON2_OUTPUT_TOO_LONG = ..., + + ARGON2_PWD_TOO_SHORT = ..., + ARGON2_PWD_TOO_LONG = ..., + + ARGON2_SALT_TOO_SHORT = ..., + ARGON2_SALT_TOO_LONG = ..., + + ARGON2_AD_TOO_SHORT = ..., + ARGON2_AD_TOO_LONG = ..., + + ARGON2_SECRET_TOO_SHORT = ..., + ARGON2_SECRET_TOO_LONG = ..., + + ARGON2_TIME_TOO_SMALL = ..., + ARGON2_TIME_TOO_LARGE = ..., + + ARGON2_MEMORY_TOO_LITTLE = ..., + ARGON2_MEMORY_TOO_MUCH = ..., + + ARGON2_LANES_TOO_FEW = ..., + ARGON2_LANES_TOO_MANY = ..., + + ARGON2_PWD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ + ARGON2_SALT_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ + ARGON2_SECRET_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ + ARGON2_AD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ + + ARGON2_MEMORY_ALLOCATION_ERROR = ..., + + ARGON2_FREE_MEMORY_CBK_NULL = ..., + ARGON2_ALLOCATE_MEMORY_CBK_NULL = ..., + + ARGON2_INCORRECT_PARAMETER = ..., + ARGON2_INCORRECT_TYPE = ..., + + ARGON2_OUT_PTR_MISMATCH = ..., + + ARGON2_THREADS_TOO_FEW = ..., + ARGON2_THREADS_TOO_MANY = ..., + + ARGON2_MISSING_ARGS = ..., + + ARGON2_ENCODING_FAIL = ..., + + ARGON2_DECODING_FAIL = ..., + + ARGON2_THREAD_FAIL = ..., + + ARGON2_DECODING_LENGTH_FAIL= ..., + + ARGON2_VERIFY_MISMATCH = ..., +} argon2_error_codes; + +#define ARGON2_FLAG_CLEAR_PASSWORD ... +#define ARGON2_FLAG_CLEAR_SECRET ... +#define ARGON2_DEFAULT_FLAGS ... + +#define ARGON2_MIN_LANES ... +#define ARGON2_MAX_LANES ... +#define ARGON2_MIN_THREADS ... +#define ARGON2_MAX_THREADS ... +#define ARGON2_SYNC_POINTS ... +#define ARGON2_MIN_OUTLEN ... +#define ARGON2_MAX_OUTLEN ... +#define ARGON2_MIN_MEMORY ... +#define ARGON2_MAX_MEMORY_BITS ... +#define ARGON2_MAX_MEMORY ... +#define ARGON2_MIN_TIME ... +#define ARGON2_MAX_TIME ... +#define ARGON2_MIN_PWD_LENGTH ... +#define ARGON2_MAX_PWD_LENGTH ... +#define ARGON2_MIN_AD_LENGTH ... +#define ARGON2_MAX_AD_LENGTH ... +#define ARGON2_MIN_SALT_LENGTH ... +#define ARGON2_MAX_SALT_LENGTH ... +#define ARGON2_MIN_SECRET ... +#define ARGON2_MAX_SECRET ... + +uint32_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, + uint32_t parallelism, uint32_t saltlen, + uint32_t hashlen, argon2_type type); + +""" +) + +if __name__ == "__main__": + ffi.compile() diff --git a/python/user_packages/Python313/site-packages/_distutils_hack/__init__.py b/python/user_packages/Python313/site-packages/_distutils_hack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94f71b99ecefd27e6cf3fd06fc3c0eef5fd73910 --- /dev/null +++ b/python/user_packages/Python313/site-packages/_distutils_hack/__init__.py @@ -0,0 +1,239 @@ +# don't import any costly modules +import os +import sys + +report_url = ( + "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml" +) + + +def warn_distutils_present(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Distutils was imported before Setuptools, but importing Setuptools " + "also replaces the `distutils` module in `sys.modules`. This may lead " + "to undesirable behaviors or errors. To avoid these issues, avoid " + "using distutils directly, ensure that setuptools is installed in the " + "traditional way (e.g. not an editable install), and/or make sure " + "that setuptools is always imported before distutils." + ) + + +def clear_distutils(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Setuptools is replacing distutils. Support for replacing " + "an already imported distutils is deprecated. In the future, " + "this condition will fail. " + f"Register concerns at {report_url}" + ) + mods = [ + name + for name in sys.modules + if name == "distutils" or name.startswith("distutils.") + ] + for name in mods: + del sys.modules[name] + + +def enabled(): + """ + Allow selection of distutils by environment variable. + """ + which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local') + if which == 'stdlib': + import warnings + + warnings.warn( + "Reliance on distutils from stdlib is deprecated. Users " + "must rely on setuptools to provide the distutils module. " + "Avoid importing distutils or import setuptools first, " + "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. " + f"Register concerns at {report_url}" + ) + return which == 'local' + + +def ensure_local_distutils(): + import importlib + + clear_distutils() + + # With the DistutilsMetaFinder in place, + # perform an import to cause distutils to be + # loaded from setuptools._distutils. Ref #2906. + with shim(): + importlib.import_module('distutils') + + # check that submodules load as expected + core = importlib.import_module('distutils.core') + assert '_distutils' in core.__file__, core.__file__ + assert 'setuptools._distutils.log' not in sys.modules + + +def do_override(): + """ + Ensure that the local copy of distutils is preferred over stdlib. + + See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 + for more motivation. + """ + if enabled(): + warn_distutils_present() + ensure_local_distutils() + + +class _TrivialRe: + def __init__(self, *patterns) -> None: + self._patterns = patterns + + def match(self, string): + return all(pat in string for pat in self._patterns) + + +class DistutilsMetaFinder: + def find_spec(self, fullname, path, target=None): + # optimization: only consider top level modules and those + # found in the CPython test suite. + if path is not None and not fullname.startswith('test.'): + return None + + method_name = 'spec_for_{fullname}'.format(**locals()) + method = getattr(self, method_name, lambda: None) + return method() + + def spec_for_distutils(self): + if self.is_cpython(): + return None + + import importlib + import importlib.abc + import importlib.util + + try: + mod = importlib.import_module('setuptools._distutils') + except Exception: + # There are a couple of cases where setuptools._distutils + # may not be present: + # - An older Setuptools without a local distutils is + # taking precedence. Ref #2957. + # - Path manipulation during sitecustomize removes + # setuptools from the path but only after the hook + # has been loaded. Ref #2980. + # In either case, fall back to stdlib behavior. + return None + + class DistutilsLoader(importlib.abc.Loader): + def create_module(self, spec): + mod.__name__ = 'distutils' + return mod + + def exec_module(self, module): + pass + + return importlib.util.spec_from_loader( + 'distutils', DistutilsLoader(), origin=mod.__file__ + ) + + @staticmethod + def is_cpython(): + """ + Suppress supplying distutils for CPython (build and tests). + Ref #2965 and #3007. + """ + return os.path.isfile('pybuilddir.txt') + + def spec_for_pip(self): + """ + Ensure stdlib distutils when running under pip. + See pypa/pip#8761 for rationale. + """ + if sys.version_info >= (3, 12) or self.pip_imported_during_build(): + return + clear_distutils() + self.spec_for_distutils = lambda: None + + @classmethod + def pip_imported_during_build(cls): + """ + Detect if pip is being imported in a build script. Ref #2355. + """ + import traceback + + return any( + cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None) + ) + + @staticmethod + def frame_file_is_setup(frame): + """ + Return True if the indicated frame suggests a setup.py file. + """ + # some frames may not have __file__ (#2940) + return frame.f_globals.get('__file__', '').endswith('setup.py') + + def spec_for_sensitive_tests(self): + """ + Ensure stdlib distutils when running select tests under CPython. + + python/cpython#91169 + """ + clear_distutils() + self.spec_for_distutils = lambda: None + + sensitive_tests = ( + [ + 'test.test_distutils', + 'test.test_peg_generator', + 'test.test_importlib', + ] + if sys.version_info < (3, 10) + else [ + 'test.test_distutils', + ] + ) + + +for name in DistutilsMetaFinder.sensitive_tests: + setattr( + DistutilsMetaFinder, + f'spec_for_{name}', + DistutilsMetaFinder.spec_for_sensitive_tests, + ) + + +DISTUTILS_FINDER = DistutilsMetaFinder() + + +def add_shim(): + DISTUTILS_FINDER in sys.meta_path or insert_shim() + + +class shim: + def __enter__(self) -> None: + insert_shim() + + def __exit__(self, exc: object, value: object, tb: object) -> None: + _remove_shim() + + +def insert_shim(): + sys.meta_path.insert(0, DISTUTILS_FINDER) + + +def _remove_shim(): + try: + sys.meta_path.remove(DISTUTILS_FINDER) + except ValueError: + pass + + +if sys.version_info < (3, 12): + # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632) + remove_shim = _remove_shim diff --git a/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52d1c011471c308d70fb16234ee4398e02ebde56 Binary files /dev/null and b/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/override.cpython-313.pyc b/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/override.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51338cf0b5263039b2dd7be77296f689aa1b86b5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/override.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/_distutils_hack/override.py b/python/user_packages/Python313/site-packages/_distutils_hack/override.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc433a4a55e3b41fa31089918fb62096092f89f --- /dev/null +++ b/python/user_packages/Python313/site-packages/_distutils_hack/override.py @@ -0,0 +1 @@ +__import__('_distutils_hack').do_override() diff --git a/python/user_packages/Python313/site-packages/_yaml/__init__.py b/python/user_packages/Python313/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/python/user_packages/Python313/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/python/user_packages/Python313/site-packages/_yaml/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/_yaml/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd228cf156d84759e8d7834b711bec038b9e6c7a Binary files /dev/null and b/python/user_packages/Python313/site-packages/_yaml/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy-2.0.49.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/sqlalchemy-2.0.49.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a21a503a3d8c764d8fb8a711f8591662d2e4651c --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy-2.0.49.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright 2005-2026 SQLAlchemy authors and contributors . + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/connectors/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a815ba92fdd1e92b8957ccc0a176f7b03e6993a --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/__init__.py @@ -0,0 +1,18 @@ +# connectors/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + + +from ..engine.interfaces import Dialect + + +class Connector(Dialect): + """Base class for dialect mixins, for DBAPIs that work + across entirely different database backends. + + Currently the only such mixin is pyodbc. + + """ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/connectors/aioodbc.py b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/aioodbc.py new file mode 100644 index 0000000000000000000000000000000000000000..625f3e32d8e288bef1c26f7e5863e06daafe5598 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/aioodbc.py @@ -0,0 +1,194 @@ +# connectors/aioodbc.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .asyncio import AsyncAdapt_dbapi_connection +from .asyncio import AsyncAdapt_dbapi_cursor +from .asyncio import AsyncAdapt_dbapi_ss_cursor +from .asyncio import AsyncAdaptFallback_dbapi_connection +from .pyodbc import PyODBCConnector +from .. import pool +from .. import util +from ..util.concurrency import await_fallback +from ..util.concurrency import await_only + + +if TYPE_CHECKING: + from ..engine.interfaces import ConnectArgsType + from ..engine.url import URL + + +class AsyncAdapt_aioodbc_cursor(AsyncAdapt_dbapi_cursor): + __slots__ = () + + def setinputsizes(self, *inputsizes): + # see https://github.com/aio-libs/aioodbc/issues/451 + return self._cursor._impl.setinputsizes(*inputsizes) + + # how it's supposed to work + # return self.await_(self._cursor.setinputsizes(*inputsizes)) + + @property + def fast_executemany(self): + return self._cursor._impl.fast_executemany + + @fast_executemany.setter + def fast_executemany(self, value): + self._cursor._impl.fast_executemany = value + + +class AsyncAdapt_aioodbc_ss_cursor( + AsyncAdapt_aioodbc_cursor, AsyncAdapt_dbapi_ss_cursor +): + __slots__ = () + + +class AsyncAdapt_aioodbc_connection(AsyncAdapt_dbapi_connection): + _cursor_cls = AsyncAdapt_aioodbc_cursor + _ss_cursor_cls = AsyncAdapt_aioodbc_ss_cursor + __slots__ = () + + @property + def autocommit(self): + return self._connection.autocommit + + @autocommit.setter + def autocommit(self, value): + # https://github.com/aio-libs/aioodbc/issues/448 + # self._connection.autocommit = value + + self._connection._conn.autocommit = value + + def ping(self, reconnect): + return self.await_(self._connection.ping(reconnect)) + + def add_output_converter(self, *arg, **kw): + self._connection.add_output_converter(*arg, **kw) + + def character_set_name(self): + return self._connection.character_set_name() + + def cursor(self, server_side=False): + # aioodbc sets connection=None when closed and just fails with + # AttributeError here. Here we use the same ProgrammingError + + # message that pyodbc uses, so it triggers is_disconnect() as well. + if self._connection.closed: + raise self.dbapi.ProgrammingError( + "Attempt to use a closed connection." + ) + return super().cursor(server_side=server_side) + + def rollback(self): + # aioodbc sets connection=None when closed and just fails with + # AttributeError here. should be a no-op + if not self._connection.closed: + super().rollback() + + def commit(self): + # aioodbc sets connection=None when closed and just fails with + # AttributeError here. should be a no-op + if not self._connection.closed: + super().commit() + + def close(self): + # aioodbc sets connection=None when closed and just fails with + # AttributeError here. should be a no-op + if not self._connection.closed: + super().close() + + +class AsyncAdaptFallback_aioodbc_connection( + AsyncAdaptFallback_dbapi_connection, AsyncAdapt_aioodbc_connection +): + __slots__ = () + + +class AsyncAdapt_aioodbc_dbapi: + def __init__(self, aioodbc, pyodbc): + self.aioodbc = aioodbc + self.pyodbc = pyodbc + self.paramstyle = pyodbc.paramstyle + self._init_dbapi_attributes() + self.Cursor = AsyncAdapt_dbapi_cursor + self.version = pyodbc.version + + def _init_dbapi_attributes(self): + for name in ( + "Warning", + "Error", + "InterfaceError", + "DataError", + "DatabaseError", + "OperationalError", + "InterfaceError", + "IntegrityError", + "ProgrammingError", + "InternalError", + "NotSupportedError", + "SQL_DRIVER_NAME", + "NUMBER", + "STRING", + "DATETIME", + "BINARY", + "Binary", + "BinaryNull", + "SQL_VARCHAR", + "SQL_WVARCHAR", + "SQL_DECIMAL", + ): + setattr(self, name, getattr(self.pyodbc, name)) + + def connect(self, *arg, **kw): + async_fallback = kw.pop("async_fallback", False) + creator_fn = kw.pop("async_creator_fn", self.aioodbc.connect) + + if util.asbool(async_fallback): + return AsyncAdaptFallback_aioodbc_connection( + self, + await_fallback(creator_fn(*arg, **kw)), + ) + else: + return AsyncAdapt_aioodbc_connection( + self, + await_only(creator_fn(*arg, **kw)), + ) + + +class aiodbcConnector(PyODBCConnector): + is_async = True + supports_statement_cache = True + + supports_server_side_cursors = True + + @classmethod + def import_dbapi(cls): + return AsyncAdapt_aioodbc_dbapi( + __import__("aioodbc"), __import__("pyodbc") + ) + + def create_connect_args(self, url: URL) -> ConnectArgsType: + arg, kw = super().create_connect_args(url) + if arg and arg[0]: + kw["dsn"] = arg[0] + + return (), kw + + @classmethod + def get_pool_class(cls, url): + async_fallback = url.query.get("async_fallback", False) + + if util.asbool(async_fallback): + return pool.FallbackAsyncAdaptedQueuePool + else: + return pool.AsyncAdaptedQueuePool + + def get_driver_connection(self, connection): + return connection._connection diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/connectors/asyncio.py b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..2016a530e0a3d898ffc1c9f97f317e6aa3af6e08 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/asyncio.py @@ -0,0 +1,429 @@ +# connectors/asyncio.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""generic asyncio-adapted versions of DBAPI connection and cursor""" + +from __future__ import annotations + +import asyncio +import collections +import sys +from typing import Any +from typing import AsyncIterator +from typing import Deque +from typing import Iterator +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING + +from ..engine import AdaptedConnection +from ..util import EMPTY_DICT +from ..util.concurrency import await_fallback +from ..util.concurrency import await_only +from ..util.concurrency import in_greenlet +from ..util.typing import Protocol + +if TYPE_CHECKING: + from ..engine.interfaces import _DBAPICursorDescription + from ..engine.interfaces import _DBAPIMultiExecuteParams + from ..engine.interfaces import _DBAPISingleExecuteParams + from ..engine.interfaces import DBAPIModule + from ..util.typing import Self + + +class AsyncIODBAPIConnection(Protocol): + """protocol representing an async adapted version of a + :pep:`249` database connection. + + + """ + + # note that async DBAPIs dont agree if close() should be awaitable, + # so it is omitted here and picked up by the __getattr__ hook below + + async def commit(self) -> None: ... + + def cursor(self, *args: Any, **kwargs: Any) -> AsyncIODBAPICursor: ... + + async def rollback(self) -> None: ... + + def __getattr__(self, key: str) -> Any: ... + + def __setattr__(self, key: str, value: Any) -> None: ... + + +class AsyncIODBAPICursor(Protocol): + """protocol representing an async adapted version + of a :pep:`249` database cursor. + + + """ + + def __aenter__(self) -> Any: ... + + @property + def description( + self, + ) -> _DBAPICursorDescription: + """The description attribute of the Cursor.""" + ... + + @property + def rowcount(self) -> int: ... + + arraysize: int + + lastrowid: int + + async def close(self) -> None: ... + + async def execute( + self, + operation: Any, + parameters: Optional[_DBAPISingleExecuteParams] = None, + ) -> Any: ... + + async def executemany( + self, + operation: Any, + parameters: _DBAPIMultiExecuteParams, + ) -> Any: ... + + async def fetchone(self) -> Optional[Any]: ... + + async def fetchmany(self, size: Optional[int] = ...) -> Sequence[Any]: ... + + async def fetchall(self) -> Sequence[Any]: ... + + async def setinputsizes(self, sizes: Sequence[Any]) -> None: ... + + def setoutputsize(self, size: Any, column: Any) -> None: ... + + async def callproc( + self, procname: str, parameters: Sequence[Any] = ... + ) -> Any: ... + + async def nextset(self) -> Optional[bool]: ... + + def __aiter__(self) -> AsyncIterator[Any]: ... + + +class AsyncAdapt_dbapi_module: + if TYPE_CHECKING: + Error = DBAPIModule.Error + OperationalError = DBAPIModule.OperationalError + InterfaceError = DBAPIModule.InterfaceError + IntegrityError = DBAPIModule.IntegrityError + + def __getattr__(self, key: str) -> Any: ... + + +class AsyncAdapt_dbapi_cursor: + server_side = False + __slots__ = ( + "_adapt_connection", + "_connection", + "await_", + "_cursor", + "_rows", + "_soft_closed_memoized", + ) + + _awaitable_cursor_close: bool = True + + _cursor: AsyncIODBAPICursor + _adapt_connection: AsyncAdapt_dbapi_connection + _connection: AsyncIODBAPIConnection + _rows: Deque[Any] + + def __init__(self, adapt_connection: AsyncAdapt_dbapi_connection): + self._adapt_connection = adapt_connection + self._connection = adapt_connection._connection + + self.await_ = adapt_connection.await_ + + cursor = self._make_new_cursor(self._connection) + self._cursor = self._aenter_cursor(cursor) + self._soft_closed_memoized = EMPTY_DICT + if not self.server_side: + self._rows = collections.deque() + + def _aenter_cursor(self, cursor: AsyncIODBAPICursor) -> AsyncIODBAPICursor: + return self.await_(cursor.__aenter__()) # type: ignore[no-any-return] + + def _make_new_cursor( + self, connection: AsyncIODBAPIConnection + ) -> AsyncIODBAPICursor: + return connection.cursor() + + @property + def description(self) -> Optional[_DBAPICursorDescription]: + if "description" in self._soft_closed_memoized: + return self._soft_closed_memoized["description"] # type: ignore[no-any-return] # noqa: E501 + return self._cursor.description + + @property + def rowcount(self) -> int: + return self._cursor.rowcount + + @property + def arraysize(self) -> int: + return self._cursor.arraysize + + @arraysize.setter + def arraysize(self, value: int) -> None: + self._cursor.arraysize = value + + @property + def lastrowid(self) -> int: + return self._cursor.lastrowid + + async def _async_soft_close(self) -> None: + """close the cursor but keep the results pending, and memoize the + description. + + .. versionadded:: 2.0.44 + + """ + + if not self._awaitable_cursor_close or self.server_side: + return + + self._soft_closed_memoized = self._soft_closed_memoized.union( + { + "description": self._cursor.description, + } + ) + await self._cursor.close() + + def close(self) -> None: + self._rows.clear() + + # updated as of 2.0.44 + # try to "close" the cursor based on what we know about the driver + # and if we are able to. otherwise, hope that the asyncio + # extension called _async_soft_close() if the cursor is going into + # a sync context + if self._cursor is None or bool(self._soft_closed_memoized): + return + + if not self._awaitable_cursor_close: + self._cursor.close() # type: ignore[unused-coroutine] + elif in_greenlet(): + self.await_(self._cursor.close()) + + def execute( + self, + operation: Any, + parameters: Optional[_DBAPISingleExecuteParams] = None, + ) -> Any: + try: + return self.await_(self._execute_async(operation, parameters)) + except Exception as error: + self._adapt_connection._handle_exception(error) + + def executemany( + self, + operation: Any, + seq_of_parameters: _DBAPIMultiExecuteParams, + ) -> Any: + try: + return self.await_( + self._executemany_async(operation, seq_of_parameters) + ) + except Exception as error: + self._adapt_connection._handle_exception(error) + + async def _execute_async( + self, operation: Any, parameters: Optional[_DBAPISingleExecuteParams] + ) -> Any: + async with self._adapt_connection._execute_mutex: + if parameters is None: + result = await self._cursor.execute(operation) + else: + result = await self._cursor.execute(operation, parameters) + + if self._cursor.description and not self.server_side: + self._rows = collections.deque(await self._cursor.fetchall()) + return result + + async def _executemany_async( + self, + operation: Any, + seq_of_parameters: _DBAPIMultiExecuteParams, + ) -> Any: + async with self._adapt_connection._execute_mutex: + return await self._cursor.executemany(operation, seq_of_parameters) + + def nextset(self) -> None: + self.await_(self._cursor.nextset()) + if self._cursor.description and not self.server_side: + self._rows = collections.deque( + self.await_(self._cursor.fetchall()) + ) + + def setinputsizes(self, *inputsizes: Any) -> None: + # NOTE: this is overridden in aioodbc due to + # see https://github.com/aio-libs/aioodbc/issues/451 + # right now + + return self.await_(self._cursor.setinputsizes(*inputsizes)) + + def __enter__(self) -> Self: + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + self.close() + + def __iter__(self) -> Iterator[Any]: + while self._rows: + yield self._rows.popleft() + + def fetchone(self) -> Optional[Any]: + if self._rows: + return self._rows.popleft() + else: + return None + + def fetchmany(self, size: Optional[int] = None) -> Sequence[Any]: + if size is None: + size = self.arraysize + rr = self._rows + return [rr.popleft() for _ in range(min(size, len(rr)))] + + def fetchall(self) -> Sequence[Any]: + retval = list(self._rows) + self._rows.clear() + return retval + + +class AsyncAdapt_dbapi_ss_cursor(AsyncAdapt_dbapi_cursor): + __slots__ = () + server_side = True + + def close(self) -> None: + if self._cursor is not None: + self.await_(self._cursor.close()) + self._cursor = None # type: ignore + + def fetchone(self) -> Optional[Any]: + return self.await_(self._cursor.fetchone()) + + def fetchmany(self, size: Optional[int] = None) -> Any: + return self.await_(self._cursor.fetchmany(size=size)) + + def fetchall(self) -> Sequence[Any]: + return self.await_(self._cursor.fetchall()) + + def __iter__(self) -> Iterator[Any]: + iterator = self._cursor.__aiter__() + while True: + try: + yield self.await_(iterator.__anext__()) + except StopAsyncIteration: + break + + +class AsyncAdapt_dbapi_connection(AdaptedConnection): + _cursor_cls = AsyncAdapt_dbapi_cursor + _ss_cursor_cls = AsyncAdapt_dbapi_ss_cursor + + await_ = staticmethod(await_only) + + __slots__ = ("dbapi", "_execute_mutex") + + _connection: AsyncIODBAPIConnection + + def __init__(self, dbapi: Any, connection: AsyncIODBAPIConnection): + self.dbapi = dbapi + self._connection = connection + self._execute_mutex = asyncio.Lock() + + def cursor(self, server_side: bool = False) -> AsyncAdapt_dbapi_cursor: + if server_side: + return self._ss_cursor_cls(self) + else: + return self._cursor_cls(self) + + def execute( + self, + operation: Any, + parameters: Optional[_DBAPISingleExecuteParams] = None, + ) -> Any: + """lots of DBAPIs seem to provide this, so include it""" + cursor = self.cursor() + cursor.execute(operation, parameters) + return cursor + + def _handle_exception(self, error: Exception) -> NoReturn: + exc_info = sys.exc_info() + + raise error.with_traceback(exc_info[2]) + + def rollback(self) -> None: + try: + self.await_(self._connection.rollback()) + except Exception as error: + self._handle_exception(error) + + def commit(self) -> None: + try: + self.await_(self._connection.commit()) + except Exception as error: + self._handle_exception(error) + + def close(self) -> None: + self.await_(self._connection.close()) + + +class AsyncAdaptFallback_dbapi_connection(AsyncAdapt_dbapi_connection): + __slots__ = () + + await_ = staticmethod(await_fallback) + + +class AsyncAdapt_terminate: + """Mixin for a AsyncAdapt_dbapi_connection to add terminate support.""" + + __slots__ = () + + def terminate(self) -> None: + if in_greenlet(): + # in a greenlet; this is the connection was invalidated case. + try: + # try to gracefully close; see #10717 + self.await_(asyncio.shield(self._terminate_graceful_close())) # type: ignore[attr-defined] # noqa: E501 + except self._terminate_handled_exceptions() as e: + # in the case where we are recycling an old connection + # that may have already been disconnected, close() will + # fail. In this case, terminate + # the connection without any further waiting. + # see issue #8419 + self._terminate_force_close() + if isinstance(e, asyncio.CancelledError): + # re-raise CancelledError if we were cancelled + raise + else: + # not in a greenlet; this is the gc cleanup case + self._terminate_force_close() + + def _terminate_handled_exceptions(self) -> Tuple[Type[BaseException], ...]: + """Returns the exceptions that should be handled when + calling _graceful_close. + """ + return (asyncio.TimeoutError, asyncio.CancelledError, OSError) + + async def _terminate_graceful_close(self) -> None: + """Try to close connection gracefully""" + raise NotImplementedError + + def _terminate_force_close(self) -> None: + """Terminate the connection""" + raise NotImplementedError diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/connectors/pyodbc.py b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/pyodbc.py new file mode 100644 index 0000000000000000000000000000000000000000..47d376f2fec5554476c7a944417c83397d46f7a0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/connectors/pyodbc.py @@ -0,0 +1,250 @@ +# connectors/pyodbc.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +import re +import typing +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple +from typing import Union +from urllib.parse import unquote_plus + +from . import Connector +from .. import ExecutionContext +from .. import pool +from .. import util +from ..engine import ConnectArgsType +from ..engine import Connection +from ..engine import interfaces +from ..engine import URL +from ..sql.type_api import TypeEngine + +if typing.TYPE_CHECKING: + from ..engine.interfaces import DBAPIModule + from ..engine.interfaces import IsolationLevel + + +class PyODBCConnector(Connector): + driver = "pyodbc" + + # this is no longer False for pyodbc in general + supports_sane_rowcount_returning = True + supports_sane_multi_rowcount = False + + supports_native_decimal = True + default_paramstyle = "named" + + fast_executemany = False + + # for non-DSN connections, this *may* be used to + # hold the desired driver name + pyodbc_driver_name: Optional[str] = None + + def __init__(self, use_setinputsizes: bool = False, **kw: Any): + super().__init__(**kw) + if use_setinputsizes: + self.bind_typing = interfaces.BindTyping.SETINPUTSIZES + + @classmethod + def import_dbapi(cls) -> DBAPIModule: + return __import__("pyodbc") + + def create_connect_args(self, url: URL) -> ConnectArgsType: + opts = url.translate_connect_args(username="user") + opts.update(url.query) + + keys = opts + + query = url.query + + connect_args: Dict[str, Any] = {} + connectors: List[str] + + for param in ("ansi", "unicode_results", "autocommit"): + if param in keys: + connect_args[param] = util.asbool(keys.pop(param)) + + if "odbc_connect" in keys: + connectors = [unquote_plus(keys.pop("odbc_connect"))] + else: + + def check_quote(token: str) -> str: + if ";" in str(token) or str(token).startswith("{"): + token = "{%s}" % token.replace("}", "}}") + return token + + keys = {k: check_quote(v) for k, v in keys.items()} + + dsn_connection = "dsn" in keys or ( + "host" in keys and "database" not in keys + ) + if dsn_connection: + connectors = [ + "dsn=%s" % (keys.pop("host", "") or keys.pop("dsn", "")) + ] + else: + port = "" + if "port" in keys and "port" not in query: + port = ",%d" % int(keys.pop("port")) + + connectors = [] + driver = keys.pop("driver", self.pyodbc_driver_name) + if driver is None and keys: + # note if keys is empty, this is a totally blank URL + util.warn( + "No driver name specified; " + "this is expected by PyODBC when using " + "DSN-less connections" + ) + else: + connectors.append("DRIVER={%s}" % driver) + + connectors.extend( + [ + "Server=%s%s" % (keys.pop("host", ""), port), + "Database=%s" % keys.pop("database", ""), + ] + ) + + user = keys.pop("user", None) + if user: + connectors.append("UID=%s" % user) + pwd = keys.pop("password", "") + if pwd: + connectors.append("PWD=%s" % pwd) + else: + authentication = keys.pop("authentication", None) + if authentication: + connectors.append("Authentication=%s" % authentication) + else: + connectors.append("Trusted_Connection=Yes") + + # if set to 'Yes', the ODBC layer will try to automagically + # convert textual data from your database encoding to your + # client encoding. This should obviously be set to 'No' if + # you query a cp1253 encoded database from a latin1 client... + if "odbc_autotranslate" in keys: + connectors.append( + "AutoTranslate=%s" % keys.pop("odbc_autotranslate") + ) + + connectors.extend(["%s=%s" % (k, v) for k, v in keys.items()]) + + return ((";".join(connectors),), connect_args) + + def is_disconnect( + self, + e: Exception, + connection: Optional[ + Union[pool.PoolProxiedConnection, interfaces.DBAPIConnection] + ], + cursor: Optional[interfaces.DBAPICursor], + ) -> bool: + if isinstance(e, self.loaded_dbapi.ProgrammingError): + return "The cursor's connection has been closed." in str( + e + ) or "Attempt to use a closed connection." in str(e) + else: + return False + + def _dbapi_version(self) -> interfaces.VersionInfoType: + if not self.dbapi: + return () + return self._parse_dbapi_version(self.dbapi.version) + + def _parse_dbapi_version(self, vers: str) -> interfaces.VersionInfoType: + m = re.match(r"(?:py.*-)?([\d\.]+)(?:-(\w+))?", vers) + if not m: + return () + vers_tuple: interfaces.VersionInfoType = tuple( + [int(x) for x in m.group(1).split(".")] + ) + if m.group(2): + vers_tuple += (m.group(2),) + return vers_tuple + + def _get_server_version_info( + self, connection: Connection + ) -> interfaces.VersionInfoType: + # NOTE: this function is not reliable, particularly when + # freetds is in use. Implement database-specific server version + # queries. + dbapi_con = connection.connection.dbapi_connection + version: Tuple[Union[int, str], ...] = () + r = re.compile(r"[.\-]") + for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)): # type: ignore[union-attr] # noqa: E501 + try: + version += (int(n),) + except ValueError: + pass + return tuple(version) + + def do_set_input_sizes( + self, + cursor: interfaces.DBAPICursor, + list_of_tuples: List[Tuple[str, Any, TypeEngine[Any]]], + context: ExecutionContext, + ) -> None: + # the rules for these types seems a little strange, as you can pass + # non-tuples as well as tuples, however it seems to assume "0" + # for the subsequent values if you don't pass a tuple which fails + # for types such as pyodbc.SQL_WLONGVARCHAR, which is the datatype + # that ticket #5649 is targeting. + + # NOTE: as of #6058, this won't be called if the use_setinputsizes + # parameter were not passed to the dialect, or if no types were + # specified in list_of_tuples + + # as of #8177 for 2.0 we assume use_setinputsizes=True and only + # omit the setinputsizes calls for .executemany() with + # fast_executemany=True + + if ( + context.execute_style is interfaces.ExecuteStyle.EXECUTEMANY + and self.fast_executemany + ): + return + + cursor.setinputsizes( + [ + ( + (dbtype, None, None) + if not isinstance(dbtype, tuple) + else dbtype + ) + for key, dbtype, sqltype in list_of_tuples + ] + ) + + def get_isolation_level_values( + self, dbapi_conn: interfaces.DBAPIConnection + ) -> List[IsolationLevel]: + return [*super().get_isolation_level_values(dbapi_conn), "AUTOCOMMIT"] + + def set_isolation_level( + self, + dbapi_connection: interfaces.DBAPIConnection, + level: IsolationLevel, + ) -> None: + # adjust for ConnectionFairy being present + # allows attribute set e.g. "connection.autocommit = True" + # to work properly + + if level == "AUTOCOMMIT": + dbapi_connection.autocommit = True + else: + dbapi_connection.autocommit = False + super().set_isolation_level(dbapi_connection, level) + + def detect_autocommit_setting( + self, dbapi_conn: interfaces.DBAPIConnection + ) -> bool: + return bool(dbapi_conn.autocommit) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b00152aca4e99284a836021c882c68d41564600 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/__init__.py @@ -0,0 +1,6 @@ +# cyextension/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/collections.pyx b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/collections.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a4d6cd4d9a2f68441c39ddabde7a0d8b7c1ac12b --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/collections.pyx @@ -0,0 +1,409 @@ +# cyextension/collections.pyx +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +cimport cython +from cpython.long cimport PyLong_FromLongLong +from cpython.set cimport PySet_Add + +from collections.abc import Collection +from itertools import filterfalse + +cdef bint add_not_present(set seen, object item, hashfunc): + hash_value = hashfunc(item) + if hash_value not in seen: + PySet_Add(seen, hash_value) + return True + else: + return False + +cdef list cunique_list(seq, hashfunc=None): + cdef set seen = set() + if not hashfunc: + return [x for x in seq if x not in seen and not PySet_Add(seen, x)] + else: + return [x for x in seq if add_not_present(seen, x, hashfunc)] + +def unique_list(seq, hashfunc=None): + return cunique_list(seq, hashfunc) + +cdef class OrderedSet(set): + + cdef list _list + + @classmethod + def __class_getitem__(cls, key): + return cls + + def __init__(self, d=None): + set.__init__(self) + if d is not None: + self._list = cunique_list(d) + set.update(self, self._list) + else: + self._list = [] + + cpdef OrderedSet copy(self): + cdef OrderedSet cp = OrderedSet.__new__(OrderedSet) + cp._list = list(self._list) + set.update(cp, cp._list) + return cp + + @cython.final + cdef OrderedSet _from_list(self, list new_list): + cdef OrderedSet new = OrderedSet.__new__(OrderedSet) + new._list = new_list + set.update(new, new_list) + return new + + def add(self, element): + if element not in self: + self._list.append(element) + PySet_Add(self, element) + + def remove(self, element): + # set.remove will raise if element is not in self + set.remove(self, element) + self._list.remove(element) + + def pop(self): + try: + value = self._list.pop() + except IndexError: + raise KeyError("pop from an empty set") from None + set.remove(self, value) + return value + + def insert(self, Py_ssize_t pos, element): + if element not in self: + self._list.insert(pos, element) + PySet_Add(self, element) + + def discard(self, element): + if element in self: + set.remove(self, element) + self._list.remove(element) + + def clear(self): + set.clear(self) + self._list = [] + + def __getitem__(self, key): + return self._list[key] + + def __iter__(self): + return iter(self._list) + + def __add__(self, other): + return self.union(other) + + def __repr__(self): + return "%s(%r)" % (self.__class__.__name__, self._list) + + __str__ = __repr__ + + def update(self, *iterables): + for iterable in iterables: + for e in iterable: + if e not in self: + self._list.append(e) + set.add(self, e) + + def __ior__(self, iterable): + self.update(iterable) + return self + + def union(self, *other): + result = self.copy() + result.update(*other) + return result + + def __or__(self, other): + return self.union(other) + + def intersection(self, *other): + cdef set other_set = set.intersection(self, *other) + return self._from_list([a for a in self._list if a in other_set]) + + def __and__(self, other): + return self.intersection(other) + + def symmetric_difference(self, other): + cdef set other_set + if isinstance(other, set): + other_set = other + collection = other_set + elif isinstance(other, Collection): + collection = other + other_set = set(other) + else: + collection = list(other) + other_set = set(collection) + result = self._from_list([a for a in self._list if a not in other_set]) + result.update(a for a in collection if a not in self) + return result + + def __xor__(self, other): + return self.symmetric_difference(other) + + def difference(self, *other): + cdef set other_set = set.difference(self, *other) + return self._from_list([a for a in self._list if a in other_set]) + + def __sub__(self, other): + return self.difference(other) + + def intersection_update(self, *other): + set.intersection_update(self, *other) + self._list = [a for a in self._list if a in self] + + def __iand__(self, other): + self.intersection_update(other) + return self + + cpdef symmetric_difference_update(self, other): + collection = other if isinstance(other, Collection) else list(other) + set.symmetric_difference_update(self, collection) + self._list = [a for a in self._list if a in self] + self._list += [a for a in collection if a in self] + + def __ixor__(self, other): + self.symmetric_difference_update(other) + return self + + def difference_update(self, *other): + set.difference_update(self, *other) + self._list = [a for a in self._list if a in self] + + def __isub__(self, other): + self.difference_update(other) + return self + +cdef object cy_id(object item): + return PyLong_FromLongLong( (item)) + +# NOTE: cython 0.x will call __add__, __sub__, etc with the parameter swapped +# instead of the __rmeth__, so they need to check that also self is of the +# correct type. This is fixed in cython 3.x. See: +# https://docs.cython.org/en/latest/src/userguide/special_methods.html#arithmetic-methods +cdef class IdentitySet: + """A set that considers only object id() for uniqueness. + + This strategy has edge cases for builtin types- it's possible to have + two 'foo' strings in one of these sets, for example. Use sparingly. + + """ + + cdef dict _members + + def __init__(self, iterable=None): + self._members = {} + if iterable: + self.update(iterable) + + def add(self, value): + self._members[cy_id(value)] = value + + def __contains__(self, value): + return cy_id(value) in self._members + + cpdef remove(self, value): + del self._members[cy_id(value)] + + def discard(self, value): + try: + self.remove(value) + except KeyError: + pass + + def pop(self): + cdef tuple pair + try: + pair = self._members.popitem() + return pair[1] + except KeyError: + raise KeyError("pop from an empty set") + + def clear(self): + self._members.clear() + + def __eq__(self, other): + cdef IdentitySet other_ + if isinstance(other, IdentitySet): + other_ = other + return self._members == other_._members + else: + return False + + def __ne__(self, other): + cdef IdentitySet other_ + if isinstance(other, IdentitySet): + other_ = other + return self._members != other_._members + else: + return True + + cpdef issubset(self, iterable): + cdef IdentitySet other + if isinstance(iterable, self.__class__): + other = iterable + else: + other = self.__class__(iterable) + + if len(self) > len(other): + return False + for m in filterfalse(other._members.__contains__, self._members): + return False + return True + + def __le__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + return self.issubset(other) + + def __lt__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + return len(self) < len(other) and self.issubset(other) + + cpdef issuperset(self, iterable): + cdef IdentitySet other + if isinstance(iterable, self.__class__): + other = iterable + else: + other = self.__class__(iterable) + + if len(self) < len(other): + return False + for m in filterfalse(self._members.__contains__, other._members): + return False + return True + + def __ge__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + return self.issuperset(other) + + def __gt__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + return len(self) > len(other) and self.issuperset(other) + + cpdef IdentitySet union(self, iterable): + cdef IdentitySet result = self.__class__() + result._members.update(self._members) + result.update(iterable) + return result + + def __or__(self, other): + if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet): + return NotImplemented + return self.union(other) + + cpdef update(self, iterable): + for obj in iterable: + self._members[cy_id(obj)] = obj + + def __ior__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + self.update(other) + return self + + cpdef IdentitySet difference(self, iterable): + cdef IdentitySet result = self.__new__(self.__class__) + if isinstance(iterable, self.__class__): + other = (iterable)._members + else: + other = {cy_id(obj) for obj in iterable} + result._members = {k:v for k, v in self._members.items() if k not in other} + return result + + def __sub__(self, other): + if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet): + return NotImplemented + return self.difference(other) + + cpdef difference_update(self, iterable): + cdef IdentitySet other = self.difference(iterable) + self._members = other._members + + def __isub__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + self.difference_update(other) + return self + + cpdef IdentitySet intersection(self, iterable): + cdef IdentitySet result = self.__new__(self.__class__) + if isinstance(iterable, self.__class__): + other = (iterable)._members + else: + other = {cy_id(obj) for obj in iterable} + result._members = {k: v for k, v in self._members.items() if k in other} + return result + + def __and__(self, other): + if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet): + return NotImplemented + return self.intersection(other) + + cpdef intersection_update(self, iterable): + cdef IdentitySet other = self.intersection(iterable) + self._members = other._members + + def __iand__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + self.intersection_update(other) + return self + + cpdef IdentitySet symmetric_difference(self, iterable): + cdef IdentitySet result = self.__new__(self.__class__) + cdef dict other + if isinstance(iterable, self.__class__): + other = (iterable)._members + else: + other = {cy_id(obj): obj for obj in iterable} + result._members = {k: v for k, v in self._members.items() if k not in other} + result._members.update( + [(k, v) for k, v in other.items() if k not in self._members] + ) + return result + + def __xor__(self, other): + if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet): + return NotImplemented + return self.symmetric_difference(other) + + cpdef symmetric_difference_update(self, iterable): + cdef IdentitySet other = self.symmetric_difference(iterable) + self._members = other._members + + def __ixor__(self, other): + if not isinstance(other, IdentitySet): + return NotImplemented + self.symmetric_difference(other) + return self + + cpdef IdentitySet copy(self): + cdef IdentitySet cp = self.__new__(self.__class__) + cp._members = self._members.copy() + return cp + + def __copy__(self): + return self.copy() + + def __len__(self): + return len(self._members) + + def __iter__(self): + return iter(self._members.values()) + + def __hash__(self): + raise TypeError("set objects are unhashable") + + def __repr__(self): + return "%s(%r)" % (type(self).__name__, list(self._members.values())) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3c73e4f23e9232818248f87616107cdf263862b7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd differ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pxd b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1fc00a15ad201daa9fd0756d066c0f50910447ec --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pxd @@ -0,0 +1,8 @@ +# cyextension/immutabledict.pxd +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +cdef class immutabledict(dict): + pass diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pyx b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pyx new file mode 100644 index 0000000000000000000000000000000000000000..7fca324215c5da78a46d2fb1b09524c217ee4681 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pyx @@ -0,0 +1,133 @@ +# cyextension/immutabledict.pyx +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from cpython.dict cimport PyDict_New, PyDict_Update, PyDict_Size + + +def _readonly_fn(obj): + raise TypeError( + "%s object is immutable and/or readonly" % obj.__class__.__name__) + + +def _immutable_fn(obj): + raise TypeError( + "%s object is immutable" % obj.__class__.__name__) + + +class ReadOnlyContainer: + + __slots__ = () + + def _readonly(self, *a,**kw): + _readonly_fn(self) + + __delitem__ = __setitem__ = __setattr__ = _readonly + + +class ImmutableDictBase(dict): + def _immutable(self, *a,**kw): + _immutable_fn(self) + + @classmethod + def __class_getitem__(cls, key): + return cls + + __delitem__ = __setitem__ = __setattr__ = _immutable + clear = pop = popitem = setdefault = update = _immutable + + +cdef class immutabledict(dict): + def __repr__(self): + return f"immutabledict({dict.__repr__(self)})" + + @classmethod + def __class_getitem__(cls, key): + return cls + + def union(self, *args, **kw): + cdef dict to_merge = None + cdef immutabledict result + cdef Py_ssize_t args_len = len(args) + if args_len > 1: + raise TypeError( + f'union expected at most 1 argument, got {args_len}' + ) + if args_len == 1: + attribute = args[0] + if isinstance(attribute, dict): + to_merge = attribute + if to_merge is None: + to_merge = dict(*args, **kw) + + if PyDict_Size(to_merge) == 0: + return self + + # new + update is faster than immutabledict(self) + result = immutabledict() + PyDict_Update(result, self) + PyDict_Update(result, to_merge) + return result + + def merge_with(self, *other): + cdef immutabledict result = None + cdef object d + cdef bint update = False + if not other: + return self + for d in other: + if d: + if update == False: + update = True + # new + update is faster than immutabledict(self) + result = immutabledict() + PyDict_Update(result, self) + PyDict_Update( + result, (d if isinstance(d, dict) else dict(d)) + ) + + return self if update == False else result + + def copy(self): + return self + + def __reduce__(self): + return immutabledict, (dict(self), ) + + def __delitem__(self, k): + _immutable_fn(self) + + def __setitem__(self, k, v): + _immutable_fn(self) + + def __setattr__(self, k, v): + _immutable_fn(self) + + def clear(self, *args, **kw): + _immutable_fn(self) + + def pop(self, *args, **kw): + _immutable_fn(self) + + def popitem(self, *args, **kw): + _immutable_fn(self) + + def setdefault(self, *args, **kw): + _immutable_fn(self) + + def update(self, *args, **kw): + _immutable_fn(self) + + # PEP 584 + def __ior__(self, other): + _immutable_fn(self) + + def __or__(self, other): + return immutabledict(dict.__or__(self, other)) + + def __ror__(self, other): + # NOTE: this is used only in cython 3.x; + # version 0.x will call __or__ with args inversed + return immutabledict(dict.__ror__(self, other)) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.cp313-win_amd64.pyd b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1592efac7004d127a143a07f621f511cf18e281b Binary files /dev/null and b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.cp313-win_amd64.pyd differ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.pyx b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.pyx new file mode 100644 index 0000000000000000000000000000000000000000..1373c71b1cc6c46afa5d3adb06ca189fc74286ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.pyx @@ -0,0 +1,68 @@ +# cyextension/processors.pyx +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +import datetime +from datetime import datetime as datetime_cls +from datetime import time as time_cls +from datetime import date as date_cls +import re + +from cpython.object cimport PyObject_Str +from cpython.unicode cimport PyUnicode_AsASCIIString, PyUnicode_Check, PyUnicode_Decode +from libc.stdio cimport sscanf + + +def int_to_boolean(value): + if value is None: + return None + return True if value else False + +def to_str(value): + return PyObject_Str(value) if value is not None else None + +def to_float(value): + return float(value) if value is not None else None + +cdef inline bytes to_bytes(object value, str type_name): + try: + return PyUnicode_AsASCIIString(value) + except Exception as e: + raise ValueError( + f"Couldn't parse {type_name} string '{value!r}' " + "- value is not a string." + ) from e + +def str_to_datetime(value): + if value is not None: + value = datetime_cls.fromisoformat(value) + return value + +def str_to_time(value): + if value is not None: + value = time_cls.fromisoformat(value) + return value + + +def str_to_date(value): + if value is not None: + value = date_cls.fromisoformat(value) + return value + + + +cdef class DecimalResultProcessor: + cdef object type_ + cdef str format_ + + def __cinit__(self, type_, format_): + self.type_ = type_ + self.format_ = format_ + + def process(self, object value): + if value is None: + return None + else: + return self.type_(self.format_ % value) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..30b6adae8f91d62b5598ff09b60c7c965792efc2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd differ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.pyx b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.pyx new file mode 100644 index 0000000000000000000000000000000000000000..121f6a1e2242158938c7b9d6d5400c19be8e4c97 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.pyx @@ -0,0 +1,102 @@ +# cyextension/resultproxy.pyx +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +import operator + +cdef class BaseRow: + cdef readonly object _parent + cdef readonly dict _key_to_index + cdef readonly tuple _data + + def __init__(self, object parent, object processors, dict key_to_index, object data): + """Row objects are constructed by CursorResult objects.""" + + self._parent = parent + + self._key_to_index = key_to_index + + if processors: + self._data = _apply_processors(processors, data) + else: + self._data = tuple(data) + + def __reduce__(self): + return ( + rowproxy_reconstructor, + (self.__class__, self.__getstate__()), + ) + + def __getstate__(self): + return {"_parent": self._parent, "_data": self._data} + + def __setstate__(self, dict state): + parent = state["_parent"] + self._parent = parent + self._data = state["_data"] + self._key_to_index = parent._key_to_index + + def _values_impl(self): + return list(self) + + def __iter__(self): + return iter(self._data) + + def __len__(self): + return len(self._data) + + def __hash__(self): + return hash(self._data) + + def __getitem__(self, index): + return self._data[index] + + def _get_by_key_impl_mapping(self, key): + return self._get_by_key_impl(key, 0) + + cdef _get_by_key_impl(self, object key, int attr_err): + index = self._key_to_index.get(key) + if index is not None: + return self._data[index] + self._parent._key_not_found(key, attr_err != 0) + + def __getattr__(self, name): + return self._get_by_key_impl(name, 1) + + def _to_tuple_instance(self): + return self._data + + +cdef tuple _apply_processors(proc, data): + res = [] + for i in range(len(proc)): + p = proc[i] + if p is None: + res.append(data[i]) + else: + res.append(p(data[i])) + return tuple(res) + + +def rowproxy_reconstructor(cls, state): + obj = cls.__new__(cls) + obj.__setstate__(state) + return obj + + +cdef int is_contiguous(tuple indexes): + cdef int i + for i in range(1, len(indexes)): + if indexes[i-1] != indexes[i] -1: + return 0 + return 1 + + +def tuplegetter(*indexes): + if len(indexes) == 1 or is_contiguous(indexes) != 0: + # slice form is faster but returns a list if input is list + return operator.itemgetter(slice(indexes[0], indexes[-1] + 1)) + else: + return operator.itemgetter(*indexes) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.cp313-win_amd64.pyd b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..50e0a2d1d34a8f3f4c4a6dbf95b4210c324af63a Binary files /dev/null and b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.cp313-win_amd64.pyd differ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.pyx b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.pyx new file mode 100644 index 0000000000000000000000000000000000000000..28dd47abd55597cb80fbd3cbabb8aec78a24f6fc --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.pyx @@ -0,0 +1,90 @@ +# cyextension/util.pyx +# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from collections.abc import Mapping + +from sqlalchemy import exc + +cdef tuple _Empty_Tuple = () + +cdef inline bint _is_mapping_or_tuple(object value): + return isinstance(value, dict) or isinstance(value, tuple) or isinstance(value, Mapping) + + +cdef inline bint _is_mapping(object value): + return isinstance(value, dict) or isinstance(value, Mapping) + + +def _distill_params_20(object params): + if params is None: + return _Empty_Tuple + elif isinstance(params, list) or isinstance(params, tuple): + if params and not _is_mapping(params[0]): + raise exc.ArgumentError( + "List argument must consist only of dictionaries" + ) + return params + elif _is_mapping(params): + return [params] + else: + raise exc.ArgumentError("mapping or list expected for parameters") + + +def _distill_raw_params(object params): + if params is None: + return _Empty_Tuple + elif isinstance(params, list): + if params and not _is_mapping_or_tuple(params[0]): + raise exc.ArgumentError( + "List argument must consist only of tuples or dictionaries" + ) + return params + elif _is_mapping_or_tuple(params): + return [params] + else: + raise exc.ArgumentError("mapping or sequence expected for parameters") + +cdef class prefix_anon_map(dict): + def __missing__(self, str key): + cdef str derived + cdef int anonymous_counter + cdef dict self_dict = self + + derived = key.split(" ", 1)[1] + + anonymous_counter = self_dict.get(derived, 1) + self_dict[derived] = anonymous_counter + 1 + value = f"{derived}_{anonymous_counter}" + self_dict[key] = value + return value + + +cdef class cache_anon_map(dict): + cdef int _index + + def __init__(self): + self._index = 0 + + def get_anon(self, obj): + cdef long long idself + cdef str id_ + cdef dict self_dict = self + + idself = id(obj) + if idself in self_dict: + return self_dict[idself], True + else: + id_ = self.__missing__(idself) + return id_, False + + def __missing__(self, key): + cdef str val + cdef dict self_dict = self + + self_dict[key] = val = str(self._index) + self._index += 1 + return val + diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/dialects/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d5e0a4b53d077e5758c4b2f286448ebef18125 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/__init__.py @@ -0,0 +1,62 @@ +# dialects/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Optional +from typing import Type +from typing import TYPE_CHECKING + +from .. import util + +if TYPE_CHECKING: + from ..engine.interfaces import Dialect + +__all__ = ("mssql", "mysql", "oracle", "postgresql", "sqlite") + + +def _auto_fn(name: str) -> Optional[Callable[[], Type[Dialect]]]: + """default dialect importer. + + plugs into the :class:`.PluginLoader` + as a first-hit system. + + """ + if "." in name: + dialect, driver = name.split(".") + else: + dialect = name + driver = "base" + + try: + if dialect == "mariadb": + # it's "OK" for us to hardcode here since _auto_fn is already + # hardcoded. if mysql / mariadb etc were third party dialects + # they would just publish all the entrypoints, which would actually + # look much nicer. + module: Any = __import__( + "sqlalchemy.dialects.mysql.mariadb" + ).dialects.mysql.mariadb + return module.loader(driver) # type: ignore + else: + module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects + module = getattr(module, dialect) + except ImportError: + return None + + if hasattr(module, driver): + module = getattr(module, driver) + return lambda: module.dialect + else: + return None + + +registry = util.PluginLoader("sqlalchemy.dialects", auto_fn=_auto_fn) + +plugins = util.PluginLoader("sqlalchemy.plugins") diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/dialects/_typing.py b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..0b5fe5121a79b607373fa249af50d0a151041a94 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/_typing.py @@ -0,0 +1,30 @@ +# dialects/_typing.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from __future__ import annotations + +from typing import Any +from typing import Iterable +from typing import Mapping +from typing import Optional +from typing import Union + +from ..sql import roles +from ..sql.base import ColumnCollection +from ..sql.schema import Column +from ..sql.schema import ColumnCollectionConstraint +from ..sql.schema import Index + + +_OnConflictConstraintT = Union[str, ColumnCollectionConstraint, Index, None] +_OnConflictIndexElementsT = Optional[ + Iterable[Union[Column[Any], str, roles.DDLConstraintColumnRole]] +] +_OnConflictIndexWhereT = Optional[roles.WhereHavingRole] +_OnConflictSetT = Optional[ + Union[Mapping[Any, Any], ColumnCollection[Any, Any]] +] +_OnConflictWhereT = Optional[roles.WhereHavingRole] diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/dialects/type_migration_guidelines.txt b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/type_migration_guidelines.txt new file mode 100644 index 0000000000000000000000000000000000000000..bb1b0e5dae07037565db359f98238cc506a6cfbd --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/dialects/type_migration_guidelines.txt @@ -0,0 +1,145 @@ +Rules for Migrating TypeEngine classes to 0.6 +--------------------------------------------- + +1. the TypeEngine classes are used for: + + a. Specifying behavior which needs to occur for bind parameters + or result row columns. + + b. Specifying types that are entirely specific to the database + in use and have no analogue in the sqlalchemy.types package. + + c. Specifying types where there is an analogue in sqlalchemy.types, + but the database in use takes vendor-specific flags for those + types. + + d. If a TypeEngine class doesn't provide any of this, it should be + *removed* from the dialect. + +2. the TypeEngine classes are *no longer* used for generating DDL. Dialects +now have a TypeCompiler subclass which uses the same visit_XXX model as +other compilers. + +3. the "ischema_names" and "colspecs" dictionaries are now required members on +the Dialect class. + +4. The names of types within dialects are now important. If a dialect-specific type +is a subclass of an existing generic type and is only provided for bind/result behavior, +the current mixed case naming can remain, i.e. _PGNumeric for Numeric - in this case, +end users would never need to use _PGNumeric directly. However, if a dialect-specific +type is specifying a type *or* arguments that are not present generically, it should +match the real name of the type on that backend, in uppercase. E.g. postgresql.INET, +mysql.ENUM, postgresql.ARRAY. + +Or follow this handy flowchart: + + is the type meant to provide bind/result is the type the same name as an + behavior to a generic type (i.e. MixedCase) ---- no ---> UPPERCASE type in types.py ? + type in types.py ? | | + | no yes + yes | | + | | does your type need special + | +<--- yes --- behavior or arguments ? + | | | + | | no + name the type using | | + _MixedCase, i.e. v V + _OracleBoolean. it name the type don't make a + stays private to the dialect identically as that type, make sure the dialect's + and is invoked *only* via within the DB, base.py imports the types.py + the colspecs dict. using UPPERCASE UPPERCASE name into its namespace + | (i.e. BIT, NCHAR, INTERVAL). + | Users can import it. + | | + v v + subclass the closest is the name of this type + MixedCase type types.py, identical to an UPPERCASE + i.e. <--- no ------- name in types.py ? + class _DateTime(types.DateTime), + class DATETIME2(types.DateTime), | + class BIT(types.TypeEngine). yes + | + v + the type should + subclass the + UPPERCASE + type in types.py + (i.e. class BLOB(types.BLOB)) + + +Example 1. pysqlite needs bind/result processing for the DateTime type in types.py, +which applies to all DateTimes and subclasses. It's named _SLDateTime and +subclasses types.DateTime. + +Example 2. MS-SQL has a TIME type which takes a non-standard "precision" argument +that is rendered within DDL. So it's named TIME in the MS-SQL dialect's base.py, +and subclasses types.TIME. Users can then say mssql.TIME(precision=10). + +Example 3. MS-SQL dialects also need special bind/result processing for date +But its DATE type doesn't render DDL differently than that of a plain +DATE, i.e. it takes no special arguments. Therefore we are just adding behavior +to types.Date, so it's named _MSDate in the MS-SQL dialect's base.py, and subclasses +types.Date. + +Example 4. MySQL has a SET type, there's no analogue for this in types.py. So +MySQL names it SET in the dialect's base.py, and it subclasses types.String, since +it ultimately deals with strings. + +Example 5. PostgreSQL has a DATETIME type. The DBAPIs handle dates correctly, +and no special arguments are used in PG's DDL beyond what types.py provides. +PostgreSQL dialect therefore imports types.DATETIME into its base.py. + +Ideally one should be able to specify a schema using names imported completely from a +dialect, all matching the real name on that backend: + + from sqlalchemy.dialects.postgresql import base as pg + + t = Table('mytable', metadata, + Column('id', pg.INTEGER, primary_key=True), + Column('name', pg.VARCHAR(300)), + Column('inetaddr', pg.INET) + ) + +where above, the INTEGER and VARCHAR types are ultimately from sqlalchemy.types, +but the PG dialect makes them available in its own namespace. + +5. "colspecs" now is a dictionary of generic or uppercased types from sqlalchemy.types +linked to types specified in the dialect. Again, if a type in the dialect does not +specify any special behavior for bind_processor() or result_processor() and does not +indicate a special type only available in this database, it must be *removed* from the +module and from this dictionary. + +6. "ischema_names" indicates string descriptions of types as returned from the database +linked to TypeEngine classes. + + a. The string name should be matched to the most specific type possible within + sqlalchemy.types, unless there is no matching type within sqlalchemy.types in which + case it points to a dialect type. *It doesn't matter* if the dialect has its + own subclass of that type with special bind/result behavior - reflect to the types.py + UPPERCASE type as much as possible. With very few exceptions, all types + should reflect to an UPPERCASE type. + + b. If the dialect contains a matching dialect-specific type that takes extra arguments + which the generic one does not, then point to the dialect-specific type. E.g. + mssql.VARCHAR takes a "collation" parameter which should be preserved. + +5. DDL, or what was formerly issued by "get_col_spec()", is now handled exclusively by +a subclass of compiler.GenericTypeCompiler. + + a. your TypeCompiler class will receive generic and uppercase types from + sqlalchemy.types. Do not assume the presence of dialect-specific attributes on + these types. + + b. the visit_UPPERCASE methods on GenericTypeCompiler should *not* be overridden with + methods that produce a different DDL name. Uppercase types don't do any kind of + "guessing" - if visit_TIMESTAMP is called, the DDL should render as TIMESTAMP in + all cases, regardless of whether or not that type is legal on the backend database. + + c. the visit_UPPERCASE methods *should* be overridden with methods that add additional + arguments and flags to those types. + + d. the visit_lowercase methods are overridden to provide an interpretation of a generic + type. E.g. visit_large_binary() might be overridden to say "return self.visit_BIT(type_)". + + e. visit_lowercase methods should *never* render strings directly - it should always + be via calling a visit_UPPERCASE() method. diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97f04aae2bfc7bb8a8acd68cb4b7fa9598f2a34c --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/__init__.py @@ -0,0 +1,62 @@ +# engine/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""SQL connections, SQL execution and high-level DB-API interface. + +The engine package defines the basic components used to interface +DB-API modules with higher-level statement construction, +connection-management, execution and result contexts. The primary +"entry point" class into this package is the Engine and its public +constructor ``create_engine()``. + +""" + +from . import events as events +from . import util as util +from .base import Connection as Connection +from .base import Engine as Engine +from .base import NestedTransaction as NestedTransaction +from .base import RootTransaction as RootTransaction +from .base import Transaction as Transaction +from .base import TwoPhaseTransaction as TwoPhaseTransaction +from .create import create_engine as create_engine +from .create import create_pool_from_url as create_pool_from_url +from .create import engine_from_config as engine_from_config +from .cursor import CursorResult as CursorResult +from .cursor import ResultProxy as ResultProxy +from .interfaces import AdaptedConnection as AdaptedConnection +from .interfaces import BindTyping as BindTyping +from .interfaces import Compiled as Compiled +from .interfaces import Connectable as Connectable +from .interfaces import ConnectArgsType as ConnectArgsType +from .interfaces import ConnectionEventsTarget as ConnectionEventsTarget +from .interfaces import CreateEnginePlugin as CreateEnginePlugin +from .interfaces import Dialect as Dialect +from .interfaces import ExceptionContext as ExceptionContext +from .interfaces import ExecutionContext as ExecutionContext +from .interfaces import TypeCompiler as TypeCompiler +from .mock import create_mock_engine as create_mock_engine +from .reflection import Inspector as Inspector +from .reflection import ObjectKind as ObjectKind +from .reflection import ObjectScope as ObjectScope +from .result import ChunkedIteratorResult as ChunkedIteratorResult +from .result import FilterResult as FilterResult +from .result import FrozenResult as FrozenResult +from .result import IteratorResult as IteratorResult +from .result import MappingResult as MappingResult +from .result import MergedResult as MergedResult +from .result import Result as Result +from .result import result_tuple as result_tuple +from .result import ScalarResult as ScalarResult +from .result import TupleResult as TupleResult +from .row import BaseRow as BaseRow +from .row import Row as Row +from .row import RowMapping as RowMapping +from .url import make_url as make_url +from .url import URL as URL +from .util import connection_memoize as connection_memoize +from ..sql import ddl as ddl diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_processors.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..83267c908d483c8d2e1ed97f5eba0a4a22bbf1e4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_processors.py @@ -0,0 +1,136 @@ +# engine/_py_processors.py +# Copyright (C) 2010-2026 the SQLAlchemy authors and contributors +# +# Copyright (C) 2010 Gaetan de Menten gdementen@gmail.com +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""defines generic type conversion functions, as used in bind and result +processors. + +They all share one common characteristic: None is passed through unchanged. + +""" + +from __future__ import annotations + +import datetime +from datetime import date as date_cls +from datetime import datetime as datetime_cls +from datetime import time as time_cls +from decimal import Decimal +import typing +from typing import Any +from typing import Callable +from typing import Optional +from typing import Type +from typing import TypeVar +from typing import Union + + +_DT = TypeVar( + "_DT", bound=Union[datetime.datetime, datetime.time, datetime.date] +) + + +def str_to_datetime_processor_factory( + regexp: typing.Pattern[str], type_: Callable[..., _DT] +) -> Callable[[Optional[str]], Optional[_DT]]: + rmatch = regexp.match + # Even on python2.6 datetime.strptime is both slower than this code + # and it does not support microseconds. + has_named_groups = bool(regexp.groupindex) + + def process(value: Optional[str]) -> Optional[_DT]: + if value is None: + return None + else: + try: + m = rmatch(value) + except TypeError as err: + raise ValueError( + "Couldn't parse %s string '%r' " + "- value is not a string." % (type_.__name__, value) + ) from err + + if m is None: + raise ValueError( + "Couldn't parse %s string: " + "'%s'" % (type_.__name__, value) + ) + if has_named_groups: + groups = m.groupdict(0) + return type_( + **dict( + list( + zip( + iter(groups.keys()), + list(map(int, iter(groups.values()))), + ) + ) + ) + ) + else: + return type_(*list(map(int, m.groups(0)))) + + return process + + +def to_decimal_processor_factory( + target_class: Type[Decimal], scale: int +) -> Callable[[Optional[float]], Optional[Decimal]]: + fstring = "%%.%df" % scale + + def process(value: Optional[float]) -> Optional[Decimal]: + if value is None: + return None + else: + return target_class(fstring % value) + + return process + + +def to_float(value: Optional[Union[int, float]]) -> Optional[float]: + if value is None: + return None + else: + return float(value) + + +def to_str(value: Optional[Any]) -> Optional[str]: + if value is None: + return None + else: + return str(value) + + +def int_to_boolean(value: Optional[int]) -> Optional[bool]: + if value is None: + return None + else: + return bool(value) + + +def str_to_datetime(value: Optional[str]) -> Optional[datetime.datetime]: + if value is not None: + dt_value = datetime_cls.fromisoformat(value) + else: + dt_value = None + return dt_value + + +def str_to_time(value: Optional[str]) -> Optional[datetime.time]: + if value is not None: + dt_value = time_cls.fromisoformat(value) + else: + dt_value = None + return dt_value + + +def str_to_date(value: Optional[str]) -> Optional[datetime.date]: + if value is not None: + dt_value = date_cls.fromisoformat(value) + else: + dt_value = None + return dt_value diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_row.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_row.py new file mode 100644 index 0000000000000000000000000000000000000000..e61f5ecb2a812820fa96e7e0b21da4fc483fa0bf --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_row.py @@ -0,0 +1,128 @@ +# engine/_py_row.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from __future__ import annotations + +import operator +import typing +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterator +from typing import List +from typing import Mapping +from typing import Optional +from typing import Tuple +from typing import Type + +if typing.TYPE_CHECKING: + from .result import _KeyType + from .result import _ProcessorsType + from .result import _RawRowType + from .result import _TupleGetterType + from .result import ResultMetaData + +MD_INDEX = 0 # integer index in cursor.description + + +class BaseRow: + __slots__ = ("_parent", "_data", "_key_to_index") + + _parent: ResultMetaData + _key_to_index: Mapping[_KeyType, int] + _data: _RawRowType + + def __init__( + self, + parent: ResultMetaData, + processors: Optional[_ProcessorsType], + key_to_index: Mapping[_KeyType, int], + data: _RawRowType, + ): + """Row objects are constructed by CursorResult objects.""" + object.__setattr__(self, "_parent", parent) + + object.__setattr__(self, "_key_to_index", key_to_index) + + if processors: + object.__setattr__( + self, + "_data", + tuple( + [ + proc(value) if proc else value + for proc, value in zip(processors, data) + ] + ), + ) + else: + object.__setattr__(self, "_data", tuple(data)) + + def __reduce__(self) -> Tuple[Callable[..., BaseRow], Tuple[Any, ...]]: + return ( + rowproxy_reconstructor, + (self.__class__, self.__getstate__()), + ) + + def __getstate__(self) -> Dict[str, Any]: + return {"_parent": self._parent, "_data": self._data} + + def __setstate__(self, state: Dict[str, Any]) -> None: + parent = state["_parent"] + object.__setattr__(self, "_parent", parent) + object.__setattr__(self, "_data", state["_data"]) + object.__setattr__(self, "_key_to_index", parent._key_to_index) + + def _values_impl(self) -> List[Any]: + return list(self) + + def __iter__(self) -> Iterator[Any]: + return iter(self._data) + + def __len__(self) -> int: + return len(self._data) + + def __hash__(self) -> int: + return hash(self._data) + + def __getitem__(self, key: Any) -> Any: + return self._data[key] + + def _get_by_key_impl_mapping(self, key: str) -> Any: + try: + return self._data[self._key_to_index[key]] + except KeyError: + pass + self._parent._key_not_found(key, False) + + def __getattr__(self, name: str) -> Any: + try: + return self._data[self._key_to_index[name]] + except KeyError: + pass + self._parent._key_not_found(name, True) + + def _to_tuple_instance(self) -> Tuple[Any, ...]: + return self._data + + +# This reconstructor is necessary so that pickles with the Cy extension or +# without use the same Binary format. +def rowproxy_reconstructor( + cls: Type[BaseRow], state: Dict[str, Any] +) -> BaseRow: + obj = cls.__new__(cls) + obj.__setstate__(state) + return obj + + +def tuplegetter(*indexes: int) -> _TupleGetterType: + if len(indexes) != 1: + for i in range(1, len(indexes)): + if indexes[i - 1] != indexes[i] - 1: + return operator.itemgetter(*indexes) + # slice form is faster but returns a list if input is list + return operator.itemgetter(slice(indexes[0], indexes[-1] + 1)) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_util.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b4b45056733b7f1f0076f2d8498c2c17b53796 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_util.py @@ -0,0 +1,74 @@ +# engine/_py_util.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from __future__ import annotations + +import typing +from typing import Any +from typing import Mapping +from typing import Optional +from typing import Tuple + +from .. import exc + +if typing.TYPE_CHECKING: + from .interfaces import _CoreAnyExecuteParams + from .interfaces import _CoreMultiExecuteParams + from .interfaces import _DBAPIAnyExecuteParams + from .interfaces import _DBAPIMultiExecuteParams + + +_no_tuple: Tuple[Any, ...] = () + + +def _distill_params_20( + params: Optional[_CoreAnyExecuteParams], +) -> _CoreMultiExecuteParams: + if params is None: + return _no_tuple + # Assume list is more likely than tuple + elif isinstance(params, list) or isinstance(params, tuple): + # collections_abc.MutableSequence): # avoid abc.__instancecheck__ + if params and not isinstance(params[0], Mapping): + raise exc.ArgumentError( + "List argument must consist only of dictionaries" + ) + + return params + elif isinstance(params, dict) or isinstance( + # only do immutabledict or abc.__instancecheck__ for Mapping after + # we've checked for plain dictionaries and would otherwise raise + params, + Mapping, + ): + return [params] + else: + raise exc.ArgumentError("mapping or list expected for parameters") + + +def _distill_raw_params( + params: Optional[_DBAPIAnyExecuteParams], +) -> _DBAPIMultiExecuteParams: + if params is None: + return _no_tuple + elif isinstance(params, list): + # collections_abc.MutableSequence): # avoid abc.__instancecheck__ + if params and not isinstance(params[0], (tuple, Mapping)): + raise exc.ArgumentError( + "List argument must consist only of tuples or dictionaries" + ) + + return params + elif isinstance(params, (tuple, dict)) or isinstance( + # only do abc.__instancecheck__ for Mapping after we've checked + # for plain dictionaries and would otherwise raise + params, + Mapping, + ): + # cast("Union[List[Mapping[str, Any]], Tuple[Any, ...]]", [params]) + return [params] # type: ignore + else: + raise exc.ArgumentError("mapping or sequence expected for parameters") diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/base.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/base.py new file mode 100644 index 0000000000000000000000000000000000000000..5a137d274359b169e8f5aff90eee75a9430f263b --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/base.py @@ -0,0 +1,3390 @@ +# engine/base.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +"""Defines :class:`_engine.Connection` and :class:`_engine.Engine`.""" +from __future__ import annotations + +import contextlib +import sys +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Tuple +from typing import Type +from typing import TypeVar +from typing import Union + +from .interfaces import BindTyping +from .interfaces import ConnectionEventsTarget +from .interfaces import DBAPICursor +from .interfaces import ExceptionContext +from .interfaces import ExecuteStyle +from .interfaces import ExecutionContext +from .interfaces import IsolationLevel +from .util import _distill_params_20 +from .util import _distill_raw_params +from .util import TransactionalContext +from .. import exc +from .. import inspection +from .. import log +from .. import util +from ..sql import compiler +from ..sql import util as sql_util + +if typing.TYPE_CHECKING: + from . import CursorResult + from . import ScalarResult + from .interfaces import _AnyExecuteParams + from .interfaces import _AnyMultiExecuteParams + from .interfaces import _CoreAnyExecuteParams + from .interfaces import _CoreMultiExecuteParams + from .interfaces import _CoreSingleExecuteParams + from .interfaces import _DBAPIAnyExecuteParams + from .interfaces import _DBAPISingleExecuteParams + from .interfaces import _ExecuteOptions + from .interfaces import CompiledCacheType + from .interfaces import CoreExecuteOptionsParameter + from .interfaces import Dialect + from .interfaces import SchemaTranslateMapType + from .reflection import Inspector # noqa + from .url import URL + from ..event import dispatcher + from ..log import _EchoFlagType + from ..pool import _ConnectionFairy + from ..pool import Pool + from ..pool import PoolProxiedConnection + from ..sql import Executable + from ..sql._typing import _InfoType + from ..sql.compiler import Compiled + from ..sql.ddl import ExecutableDDLElement + from ..sql.ddl import InvokeDDLBase + from ..sql.functions import FunctionElement + from ..sql.schema import DefaultGenerator + from ..sql.schema import HasSchemaAttr + from ..sql.schema import SchemaVisitable + from ..sql.selectable import TypedReturnsRows + + +_T = TypeVar("_T", bound=Any) +_EMPTY_EXECUTION_OPTS: _ExecuteOptions = util.EMPTY_DICT +NO_OPTIONS: Mapping[str, Any] = util.EMPTY_DICT + + +class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): + """Provides high-level functionality for a wrapped DB-API connection. + + The :class:`_engine.Connection` object is procured by calling the + :meth:`_engine.Engine.connect` method of the :class:`_engine.Engine` + object, and provides services for execution of SQL statements as well + as transaction control. + + The Connection object is **not** thread-safe. While a Connection can be + shared among threads using properly synchronized access, it is still + possible that the underlying DBAPI connection may not support shared + access between threads. Check the DBAPI documentation for details. + + The Connection object represents a single DBAPI connection checked out + from the connection pool. In this state, the connection pool has no + affect upon the connection, including its expiration or timeout state. + For the connection pool to properly manage connections, connections + should be returned to the connection pool (i.e. ``connection.close()``) + whenever the connection is not in use. + + .. index:: + single: thread safety; Connection + + """ + + dialect: Dialect + dispatch: dispatcher[ConnectionEventsTarget] + + _sqla_logger_namespace = "sqlalchemy.engine.Connection" + + # used by sqlalchemy.engine.util.TransactionalContext + _trans_context_manager: Optional[TransactionalContext] = None + + # legacy as of 2.0, should be eventually deprecated and + # removed. was used in the "pre_ping" recipe that's been in the docs + # a long time + should_close_with_result = False + + _dbapi_connection: Optional[PoolProxiedConnection] + + _execution_options: _ExecuteOptions + + _transaction: Optional[RootTransaction] + _nested_transaction: Optional[NestedTransaction] + + def __init__( + self, + engine: Engine, + connection: Optional[PoolProxiedConnection] = None, + _has_events: Optional[bool] = None, + _allow_revalidate: bool = True, + _allow_autobegin: bool = True, + ): + """Construct a new Connection.""" + self.engine = engine + self.dialect = dialect = engine.dialect + + if connection is None: + try: + self._dbapi_connection = engine.raw_connection() + except dialect.loaded_dbapi.Error as err: + Connection._handle_dbapi_exception_noconnection( + err, dialect, engine + ) + raise + else: + self._dbapi_connection = connection + + self._transaction = self._nested_transaction = None + self.__savepoint_seq = 0 + self.__in_begin = False + + self.__can_reconnect = _allow_revalidate + self._allow_autobegin = _allow_autobegin + self._echo = self.engine._should_log_info() + + if _has_events is None: + # if _has_events is sent explicitly as False, + # then don't join the dispatch of the engine; we don't + # want to handle any of the engine's events in that case. + self.dispatch = self.dispatch._join(engine.dispatch) + self._has_events = _has_events or ( + _has_events is None and engine._has_events + ) + + self._execution_options = engine._execution_options + + if self._has_events or self.engine._has_events: + self.dispatch.engine_connect(self) + + # this can be assigned differently via + # characteristics.LoggingTokenCharacteristic + _message_formatter: Any = None + + def _log_info(self, message: str, *arg: Any, **kw: Any) -> None: + fmt = self._message_formatter + + if fmt: + message = fmt(message) + + if log.STACKLEVEL: + kw["stacklevel"] = 1 + log.STACKLEVEL_OFFSET + + self.engine.logger.info(message, *arg, **kw) + + def _log_debug(self, message: str, *arg: Any, **kw: Any) -> None: + fmt = self._message_formatter + + if fmt: + message = fmt(message) + + if log.STACKLEVEL: + kw["stacklevel"] = 1 + log.STACKLEVEL_OFFSET + + self.engine.logger.debug(message, *arg, **kw) + + @property + def _schema_translate_map(self) -> Optional[SchemaTranslateMapType]: + schema_translate_map: Optional[SchemaTranslateMapType] = ( + self._execution_options.get("schema_translate_map", None) + ) + + return schema_translate_map + + def schema_for_object(self, obj: HasSchemaAttr) -> Optional[str]: + """Return the schema name for the given schema item taking into + account current schema translate map. + + """ + + name = obj.schema + schema_translate_map: Optional[SchemaTranslateMapType] = ( + self._execution_options.get("schema_translate_map", None) + ) + + if ( + schema_translate_map + and name in schema_translate_map + and obj._use_schema_map + ): + return schema_translate_map[name] + else: + return name + + def __enter__(self) -> Connection: + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + self.close() + + @overload + def execution_options( + self, + *, + compiled_cache: Optional[CompiledCacheType] = ..., + logging_token: str = ..., + isolation_level: IsolationLevel = ..., + no_parameters: bool = False, + stream_results: bool = False, + max_row_buffer: int = ..., + yield_per: int = ..., + insertmanyvalues_page_size: int = ..., + schema_translate_map: Optional[SchemaTranslateMapType] = ..., + preserve_rowcount: bool = False, + **opt: Any, + ) -> Connection: ... + + @overload + def execution_options(self, **opt: Any) -> Connection: ... + + def execution_options(self, **opt: Any) -> Connection: + r"""Set non-SQL options for the connection which take effect + during execution. + + This method modifies this :class:`_engine.Connection` **in-place**; + the return value is the same :class:`_engine.Connection` object + upon which the method is called. Note that this is in contrast + to the behavior of the ``execution_options`` methods on other + objects such as :meth:`_engine.Engine.execution_options` and + :meth:`_sql.Executable.execution_options`. The rationale is that many + such execution options necessarily modify the state of the base + DBAPI connection in any case so there is no feasible means of + keeping the effect of such an option localized to a "sub" connection. + + .. versionchanged:: 2.0 The :meth:`_engine.Connection.execution_options` + method, in contrast to other objects with this method, modifies + the connection in-place without creating copy of it. + + As discussed elsewhere, the :meth:`_engine.Connection.execution_options` + method accepts any arbitrary parameters including user defined names. + All parameters given are consumable in a number of ways including + by using the :meth:`_engine.Connection.get_execution_options` method. + See the examples at :meth:`_sql.Executable.execution_options` + and :meth:`_engine.Engine.execution_options`. + + The keywords that are currently recognized by SQLAlchemy itself + include all those listed under :meth:`.Executable.execution_options`, + as well as others that are specific to :class:`_engine.Connection`. + + :param compiled_cache: Available on: :class:`_engine.Connection`, + :class:`_engine.Engine`. + + A dictionary where :class:`.Compiled` objects + will be cached when the :class:`_engine.Connection` + compiles a clause + expression into a :class:`.Compiled` object. This dictionary will + supersede the statement cache that may be configured on the + :class:`_engine.Engine` itself. If set to None, caching + is disabled, even if the engine has a configured cache size. + + Note that the ORM makes use of its own "compiled" caches for + some operations, including flush operations. The caching + used by the ORM internally supersedes a cache dictionary + specified here. + + :param logging_token: Available on: :class:`_engine.Connection`, + :class:`_engine.Engine`, :class:`_sql.Executable`. + + Adds the specified string token surrounded by brackets in log + messages logged by the connection, i.e. the logging that's enabled + either via the :paramref:`_sa.create_engine.echo` flag or via the + ``logging.getLogger("sqlalchemy.engine")`` logger. This allows a + per-connection or per-sub-engine token to be available which is + useful for debugging concurrent connection scenarios. + + .. versionadded:: 1.4.0b2 + + .. seealso:: + + :ref:`dbengine_logging_tokens` - usage example + + :paramref:`_sa.create_engine.logging_name` - adds a name to the + name used by the Python logger object itself. + + :param isolation_level: Available on: :class:`_engine.Connection`, + :class:`_engine.Engine`. + + Set the transaction isolation level for the lifespan of this + :class:`_engine.Connection` object. + Valid values include those string + values accepted by the :paramref:`_sa.create_engine.isolation_level` + parameter passed to :func:`_sa.create_engine`. These levels are + semi-database specific; see individual dialect documentation for + valid levels. + + The isolation level option applies the isolation level by emitting + statements on the DBAPI connection, and **necessarily affects the + original Connection object overall**. The isolation level will remain + at the given setting until explicitly changed, or when the DBAPI + connection itself is :term:`released` to the connection pool, i.e. the + :meth:`_engine.Connection.close` method is called, at which time an + event handler will emit additional statements on the DBAPI connection + in order to revert the isolation level change. + + .. note:: The ``isolation_level`` execution option may only be + established before the :meth:`_engine.Connection.begin` method is + called, as well as before any SQL statements are emitted which + would otherwise trigger "autobegin", or directly after a call to + :meth:`_engine.Connection.commit` or + :meth:`_engine.Connection.rollback`. A database cannot change the + isolation level on a transaction in progress. + + .. note:: The ``isolation_level`` execution option is implicitly + reset if the :class:`_engine.Connection` is invalidated, e.g. via + the :meth:`_engine.Connection.invalidate` method, or if a + disconnection error occurs. The new connection produced after the + invalidation will **not** have the selected isolation level + re-applied to it automatically. + + .. seealso:: + + :ref:`dbapi_autocommit` + + :meth:`_engine.Connection.get_isolation_level` + - view current actual level + + :param no_parameters: Available on: :class:`_engine.Connection`, + :class:`_sql.Executable`. + + When ``True``, if the final parameter + list or dictionary is totally empty, will invoke the + statement on the cursor as ``cursor.execute(statement)``, + not passing the parameter collection at all. + Some DBAPIs such as psycopg2 and mysql-python consider + percent signs as significant only when parameters are + present; this option allows code to generate SQL + containing percent signs (and possibly other characters) + that is neutral regarding whether it's executed by the DBAPI + or piped into a script that's later invoked by + command line tools. + + :param stream_results: Available on: :class:`_engine.Connection`, + :class:`_sql.Executable`. + + Indicate to the dialect that results should be "streamed" and not + pre-buffered, if possible. For backends such as PostgreSQL, MySQL + and MariaDB, this indicates the use of a "server side cursor" as + opposed to a client side cursor. Other backends such as that of + Oracle Database may already use server side cursors by default. + + The usage of + :paramref:`_engine.Connection.execution_options.stream_results` is + usually combined with setting a fixed number of rows to to be fetched + in batches, to allow for efficient iteration of database rows while + at the same time not loading all result rows into memory at once; + this can be configured on a :class:`_engine.Result` object using the + :meth:`_engine.Result.yield_per` method, after execution has + returned a new :class:`_engine.Result`. If + :meth:`_engine.Result.yield_per` is not used, + the :paramref:`_engine.Connection.execution_options.stream_results` + mode of operation will instead use a dynamically sized buffer + which buffers sets of rows at a time, growing on each batch + based on a fixed growth size up until a limit which may + be configured using the + :paramref:`_engine.Connection.execution_options.max_row_buffer` + parameter. + + When using the ORM to fetch ORM mapped objects from a result, + :meth:`_engine.Result.yield_per` should always be used with + :paramref:`_engine.Connection.execution_options.stream_results`, + so that the ORM does not fetch all rows into new ORM objects at once. + + For typical use, the + :paramref:`_engine.Connection.execution_options.yield_per` execution + option should be preferred, which sets up both + :paramref:`_engine.Connection.execution_options.stream_results` and + :meth:`_engine.Result.yield_per` at once. This option is supported + both at a core level by :class:`_engine.Connection` as well as by the + ORM :class:`_engine.Session`; the latter is described at + :ref:`orm_queryguide_yield_per`. + + .. seealso:: + + :ref:`engine_stream_results` - background on + :paramref:`_engine.Connection.execution_options.stream_results` + + :paramref:`_engine.Connection.execution_options.max_row_buffer` + + :paramref:`_engine.Connection.execution_options.yield_per` + + :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` + describing the ORM version of ``yield_per`` + + :param max_row_buffer: Available on: :class:`_engine.Connection`, + :class:`_sql.Executable`. Sets a maximum + buffer size to use when the + :paramref:`_engine.Connection.execution_options.stream_results` + execution option is used on a backend that supports server side + cursors. The default value if not specified is 1000. + + .. seealso:: + + :paramref:`_engine.Connection.execution_options.stream_results` + + :ref:`engine_stream_results` + + + :param yield_per: Available on: :class:`_engine.Connection`, + :class:`_sql.Executable`. Integer value applied which will + set the :paramref:`_engine.Connection.execution_options.stream_results` + execution option and invoke :meth:`_engine.Result.yield_per` + automatically at once. Allows equivalent functionality as + is present when using this parameter with the ORM. + + .. versionadded:: 1.4.40 + + .. seealso:: + + :ref:`engine_stream_results` - background and examples + on using server side cursors with Core. + + :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` + describing the ORM version of ``yield_per`` + + :param insertmanyvalues_page_size: Available on: :class:`_engine.Connection`, + :class:`_engine.Engine`. Number of rows to format into an + INSERT statement when the statement uses "insertmanyvalues" mode, + which is a paged form of bulk insert that is used for many backends + when using :term:`executemany` execution typically in conjunction + with RETURNING. Defaults to 1000. May also be modified on a + per-engine basis using the + :paramref:`_sa.create_engine.insertmanyvalues_page_size` parameter. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + :param schema_translate_map: Available on: :class:`_engine.Connection`, + :class:`_engine.Engine`, :class:`_sql.Executable`. + + A dictionary mapping schema names to schema names, that will be + applied to the :paramref:`_schema.Table.schema` element of each + :class:`_schema.Table` + encountered when SQL or DDL expression elements + are compiled into strings; the resulting schema name will be + converted based on presence in the map of the original name. + + .. seealso:: + + :ref:`schema_translating` + + :param preserve_rowcount: Boolean; when True, the ``cursor.rowcount`` + attribute will be unconditionally memoized within the result and + made available via the :attr:`.CursorResult.rowcount` attribute. + Normally, this attribute is only preserved for UPDATE and DELETE + statements. Using this option, the DBAPIs rowcount value can + be accessed for other kinds of statements such as INSERT and SELECT, + to the degree that the DBAPI supports these statements. See + :attr:`.CursorResult.rowcount` for notes regarding the behavior + of this attribute. + + .. versionadded:: 2.0.28 + + .. seealso:: + + :meth:`_engine.Engine.execution_options` + + :meth:`.Executable.execution_options` + + :meth:`_engine.Connection.get_execution_options` + + :ref:`orm_queryguide_execution_options` - documentation on all + ORM-specific execution options + + """ # noqa + if self._has_events or self.engine._has_events: + self.dispatch.set_connection_execution_options(self, opt) + self._execution_options = self._execution_options.union(opt) + self.dialect.set_connection_execution_options(self, opt) + return self + + def get_execution_options(self) -> _ExecuteOptions: + """Get the non-SQL options which will take effect during execution. + + .. versionadded:: 1.3 + + .. seealso:: + + :meth:`_engine.Connection.execution_options` + """ + return self._execution_options + + @property + def _still_open_and_dbapi_connection_is_valid(self) -> bool: + pool_proxied_connection = self._dbapi_connection + return ( + pool_proxied_connection is not None + and pool_proxied_connection.is_valid + ) + + @property + def closed(self) -> bool: + """Return True if this connection is closed.""" + + return self._dbapi_connection is None and not self.__can_reconnect + + @property + def invalidated(self) -> bool: + """Return True if this connection was invalidated. + + This does not indicate whether or not the connection was + invalidated at the pool level, however + + """ + + # prior to 1.4, "invalid" was stored as a state independent of + # "closed", meaning an invalidated connection could be "closed", + # the _dbapi_connection would be None and closed=True, yet the + # "invalid" flag would stay True. This meant that there were + # three separate states (open/valid, closed/valid, closed/invalid) + # when there is really no reason for that; a connection that's + # "closed" does not need to be "invalid". So the state is now + # represented by the two facts alone. + + pool_proxied_connection = self._dbapi_connection + return pool_proxied_connection is None and self.__can_reconnect + + @property + def connection(self) -> PoolProxiedConnection: + """The underlying DB-API connection managed by this Connection. + + This is a SQLAlchemy connection-pool proxied connection + which then has the attribute + :attr:`_pool._ConnectionFairy.dbapi_connection` that refers to the + actual driver connection. + + .. seealso:: + + + :ref:`dbapi_connections` + + """ + + if self._dbapi_connection is None: + try: + return self._revalidate_connection() + except (exc.PendingRollbackError, exc.ResourceClosedError): + raise + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + else: + return self._dbapi_connection + + def get_isolation_level(self) -> IsolationLevel: + """Return the current **actual** isolation level that's present on + the database within the scope of this connection. + + This attribute will perform a live SQL operation against the database + in order to procure the current isolation level, so the value returned + is the actual level on the underlying DBAPI connection regardless of + how this state was set. This will be one of the four actual isolation + modes ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``, + ``SERIALIZABLE``. It will **not** include the ``AUTOCOMMIT`` isolation + level setting. Third party dialects may also feature additional + isolation level settings. + + .. note:: This method **will not report** on the ``AUTOCOMMIT`` + isolation level, which is a separate :term:`dbapi` setting that's + independent of **actual** isolation level. When ``AUTOCOMMIT`` is + in use, the database connection still has a "traditional" isolation + mode in effect, that is typically one of the four values + ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``, + ``SERIALIZABLE``. + + Compare to the :attr:`_engine.Connection.default_isolation_level` + accessor which returns the isolation level that is present on the + database at initial connection time. + + .. seealso:: + + :attr:`_engine.Connection.default_isolation_level` + - view default level + + :paramref:`_sa.create_engine.isolation_level` + - set per :class:`_engine.Engine` isolation level + + :paramref:`.Connection.execution_options.isolation_level` + - set per :class:`_engine.Connection` isolation level + + """ + dbapi_connection = self.connection.dbapi_connection + assert dbapi_connection is not None + try: + return self.dialect.get_isolation_level(dbapi_connection) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + @property + def default_isolation_level(self) -> Optional[IsolationLevel]: + """The initial-connection time isolation level associated with the + :class:`_engine.Dialect` in use. + + This value is independent of the + :paramref:`.Connection.execution_options.isolation_level` and + :paramref:`.Engine.execution_options.isolation_level` execution + options, and is determined by the :class:`_engine.Dialect` when the + first connection is created, by performing a SQL query against the + database for the current isolation level before any additional commands + have been emitted. + + Calling this accessor does not invoke any new SQL queries. + + .. seealso:: + + :meth:`_engine.Connection.get_isolation_level` + - view current actual isolation level + + :paramref:`_sa.create_engine.isolation_level` + - set per :class:`_engine.Engine` isolation level + + :paramref:`.Connection.execution_options.isolation_level` + - set per :class:`_engine.Connection` isolation level + + """ + return self.dialect.default_isolation_level + + def _invalid_transaction(self) -> NoReturn: + raise exc.PendingRollbackError( + "Can't reconnect until invalid %stransaction is rolled " + "back. Please rollback() fully before proceeding" + % ("savepoint " if self._nested_transaction is not None else ""), + code="8s2b", + ) + + def _revalidate_connection(self) -> PoolProxiedConnection: + if self.__can_reconnect and self.invalidated: + if self._transaction is not None: + self._invalid_transaction() + self._dbapi_connection = self.engine.raw_connection() + return self._dbapi_connection + raise exc.ResourceClosedError("This Connection is closed") + + @property + def info(self) -> _InfoType: + """Info dictionary associated with the underlying DBAPI connection + referred to by this :class:`_engine.Connection`, allowing user-defined + data to be associated with the connection. + + The data here will follow along with the DBAPI connection including + after it is returned to the connection pool and used again + in subsequent instances of :class:`_engine.Connection`. + + """ + + return self.connection.info + + def invalidate(self, exception: Optional[BaseException] = None) -> None: + """Invalidate the underlying DBAPI connection associated with + this :class:`_engine.Connection`. + + An attempt will be made to close the underlying DBAPI connection + immediately; however if this operation fails, the error is logged + but not raised. The connection is then discarded whether or not + close() succeeded. + + Upon the next use (where "use" typically means using the + :meth:`_engine.Connection.execute` method or similar), + this :class:`_engine.Connection` will attempt to + procure a new DBAPI connection using the services of the + :class:`_pool.Pool` as a source of connectivity (e.g. + a "reconnection"). + + If a transaction was in progress (e.g. the + :meth:`_engine.Connection.begin` method has been called) when + :meth:`_engine.Connection.invalidate` method is called, at the DBAPI + level all state associated with this transaction is lost, as + the DBAPI connection is closed. The :class:`_engine.Connection` + will not allow a reconnection to proceed until the + :class:`.Transaction` object is ended, by calling the + :meth:`.Transaction.rollback` method; until that point, any attempt at + continuing to use the :class:`_engine.Connection` will raise an + :class:`~sqlalchemy.exc.InvalidRequestError`. + This is to prevent applications from accidentally + continuing an ongoing transactional operations despite the + fact that the transaction has been lost due to an + invalidation. + + The :meth:`_engine.Connection.invalidate` method, + just like auto-invalidation, + will at the connection pool level invoke the + :meth:`_events.PoolEvents.invalidate` event. + + :param exception: an optional ``Exception`` instance that's the + reason for the invalidation. is passed along to event handlers + and logging functions. + + .. seealso:: + + :ref:`pool_connection_invalidation` + + """ + + if self.invalidated: + return + + if self.closed: + raise exc.ResourceClosedError("This Connection is closed") + + if self._still_open_and_dbapi_connection_is_valid: + pool_proxied_connection = self._dbapi_connection + assert pool_proxied_connection is not None + pool_proxied_connection.invalidate(exception) + + self._dbapi_connection = None + + def detach(self) -> None: + """Detach the underlying DB-API connection from its connection pool. + + E.g.:: + + with engine.connect() as conn: + conn.detach() + conn.execute(text("SET search_path TO schema1, schema2")) + + # work with connection + + # connection is fully closed (since we used "with:", can + # also call .close()) + + This :class:`_engine.Connection` instance will remain usable. + When closed + (or exited from a context manager context as above), + the DB-API connection will be literally closed and not + returned to its originating pool. + + This method can be used to insulate the rest of an application + from a modified state on a connection (such as a transaction + isolation level or similar). + + """ + + if self.closed: + raise exc.ResourceClosedError("This Connection is closed") + + pool_proxied_connection = self._dbapi_connection + if pool_proxied_connection is None: + raise exc.InvalidRequestError( + "Can't detach an invalidated Connection" + ) + pool_proxied_connection.detach() + + def _autobegin(self) -> None: + if self._allow_autobegin and not self.__in_begin: + self.begin() + + def begin(self) -> RootTransaction: + """Begin a transaction prior to autobegin occurring. + + E.g.:: + + with engine.connect() as conn: + with conn.begin() as trans: + conn.execute(table.insert(), {"username": "sandy"}) + + The returned object is an instance of :class:`_engine.RootTransaction`. + This object represents the "scope" of the transaction, + which completes when either the :meth:`_engine.Transaction.rollback` + or :meth:`_engine.Transaction.commit` method is called; the object + also works as a context manager as illustrated above. + + The :meth:`_engine.Connection.begin` method begins a + transaction that normally will be begun in any case when the connection + is first used to execute a statement. The reason this method might be + used would be to invoke the :meth:`_events.ConnectionEvents.begin` + event at a specific time, or to organize code within the scope of a + connection checkout in terms of context managed blocks, such as:: + + with engine.connect() as conn: + with conn.begin(): + conn.execute(...) + conn.execute(...) + + with conn.begin(): + conn.execute(...) + conn.execute(...) + + The above code is not fundamentally any different in its behavior than + the following code which does not use + :meth:`_engine.Connection.begin`; the below style is known + as "commit as you go" style:: + + with engine.connect() as conn: + conn.execute(...) + conn.execute(...) + conn.commit() + + conn.execute(...) + conn.execute(...) + conn.commit() + + From a database point of view, the :meth:`_engine.Connection.begin` + method does not emit any SQL or change the state of the underlying + DBAPI connection in any way; the Python DBAPI does not have any + concept of explicit transaction begin. + + .. seealso:: + + :ref:`tutorial_working_with_transactions` - in the + :ref:`unified_tutorial` + + :meth:`_engine.Connection.begin_nested` - use a SAVEPOINT + + :meth:`_engine.Connection.begin_twophase` - + use a two phase /XID transaction + + :meth:`_engine.Engine.begin` - context manager available from + :class:`_engine.Engine` + + """ + if self._transaction is None: + self._transaction = RootTransaction(self) + return self._transaction + else: + raise exc.InvalidRequestError( + "This connection has already initialized a SQLAlchemy " + "Transaction() object via begin() or autobegin; can't " + "call begin() here unless rollback() or commit() " + "is called first." + ) + + def begin_nested(self) -> NestedTransaction: + """Begin a nested transaction (i.e. SAVEPOINT) and return a transaction + handle that controls the scope of the SAVEPOINT. + + E.g.:: + + with engine.begin() as connection: + with connection.begin_nested(): + connection.execute(table.insert(), {"username": "sandy"}) + + The returned object is an instance of + :class:`_engine.NestedTransaction`, which includes transactional + methods :meth:`_engine.NestedTransaction.commit` and + :meth:`_engine.NestedTransaction.rollback`; for a nested transaction, + these methods correspond to the operations "RELEASE SAVEPOINT " + and "ROLLBACK TO SAVEPOINT ". The name of the savepoint is local + to the :class:`_engine.NestedTransaction` object and is generated + automatically. Like any other :class:`_engine.Transaction`, the + :class:`_engine.NestedTransaction` may be used as a context manager as + illustrated above which will "release" or "rollback" corresponding to + if the operation within the block were successful or raised an + exception. + + Nested transactions require SAVEPOINT support in the underlying + database, else the behavior is undefined. SAVEPOINT is commonly used to + run operations within a transaction that may fail, while continuing the + outer transaction. E.g.:: + + from sqlalchemy import exc + + with engine.begin() as connection: + trans = connection.begin_nested() + try: + connection.execute(table.insert(), {"username": "sandy"}) + trans.commit() + except exc.IntegrityError: # catch for duplicate username + trans.rollback() # rollback to savepoint + + # outer transaction continues + connection.execute(...) + + If :meth:`_engine.Connection.begin_nested` is called without first + calling :meth:`_engine.Connection.begin` or + :meth:`_engine.Engine.begin`, the :class:`_engine.Connection` object + will "autobegin" the outer transaction first. This outer transaction + may be committed using "commit-as-you-go" style, e.g.:: + + with engine.connect() as connection: # begin() wasn't called + + with connection.begin_nested(): # will auto-"begin()" first + connection.execute(...) + # savepoint is released + + connection.execute(...) + + # explicitly commit outer transaction + connection.commit() + + # can continue working with connection here + + .. versionchanged:: 2.0 + + :meth:`_engine.Connection.begin_nested` will now participate + in the connection "autobegin" behavior that is new as of + 2.0 / "future" style connections in 1.4. + + .. seealso:: + + :meth:`_engine.Connection.begin` + + :ref:`session_begin_nested` - ORM support for SAVEPOINT + + """ + if self._transaction is None: + self._autobegin() + + return NestedTransaction(self) + + def begin_twophase(self, xid: Optional[Any] = None) -> TwoPhaseTransaction: + """Begin a two-phase or XA transaction and return a transaction + handle. + + The returned object is an instance of :class:`.TwoPhaseTransaction`, + which in addition to the methods provided by + :class:`.Transaction`, also provides a + :meth:`~.TwoPhaseTransaction.prepare` method. + + :param xid: the two phase transaction id. If not supplied, a + random id will be generated. + + .. seealso:: + + :meth:`_engine.Connection.begin` + + :meth:`_engine.Connection.begin_twophase` + + """ + + if self._transaction is not None: + raise exc.InvalidRequestError( + "Cannot start a two phase transaction when a transaction " + "is already in progress." + ) + if xid is None: + xid = self.engine.dialect.create_xid() + return TwoPhaseTransaction(self, xid) + + def commit(self) -> None: + """Commit the transaction that is currently in progress. + + This method commits the current transaction if one has been started. + If no transaction was started, the method has no effect, assuming + the connection is in a non-invalidated state. + + A transaction is begun on a :class:`_engine.Connection` automatically + whenever a statement is first executed, or when the + :meth:`_engine.Connection.begin` method is called. + + .. note:: The :meth:`_engine.Connection.commit` method only acts upon + the primary database transaction that is linked to the + :class:`_engine.Connection` object. It does not operate upon a + SAVEPOINT that would have been invoked from the + :meth:`_engine.Connection.begin_nested` method; for control of a + SAVEPOINT, call :meth:`_engine.NestedTransaction.commit` on the + :class:`_engine.NestedTransaction` that is returned by the + :meth:`_engine.Connection.begin_nested` method itself. + + + """ + if self._transaction: + self._transaction.commit() + + def rollback(self) -> None: + """Roll back the transaction that is currently in progress. + + This method rolls back the current transaction if one has been started. + If no transaction was started, the method has no effect. If a + transaction was started and the connection is in an invalidated state, + the transaction is cleared using this method. + + A transaction is begun on a :class:`_engine.Connection` automatically + whenever a statement is first executed, or when the + :meth:`_engine.Connection.begin` method is called. + + .. note:: The :meth:`_engine.Connection.rollback` method only acts + upon the primary database transaction that is linked to the + :class:`_engine.Connection` object. It does not operate upon a + SAVEPOINT that would have been invoked from the + :meth:`_engine.Connection.begin_nested` method; for control of a + SAVEPOINT, call :meth:`_engine.NestedTransaction.rollback` on the + :class:`_engine.NestedTransaction` that is returned by the + :meth:`_engine.Connection.begin_nested` method itself. + + + """ + if self._transaction: + self._transaction.rollback() + + def recover_twophase(self) -> List[Any]: + return self.engine.dialect.do_recover_twophase(self) + + def rollback_prepared(self, xid: Any, recover: bool = False) -> None: + self.engine.dialect.do_rollback_twophase(self, xid, recover=recover) + + def commit_prepared(self, xid: Any, recover: bool = False) -> None: + self.engine.dialect.do_commit_twophase(self, xid, recover=recover) + + def in_transaction(self) -> bool: + """Return True if a transaction is in progress.""" + return self._transaction is not None and self._transaction.is_active + + def in_nested_transaction(self) -> bool: + """Return True if a transaction is in progress.""" + return ( + self._nested_transaction is not None + and self._nested_transaction.is_active + ) + + def _is_autocommit_isolation(self) -> bool: + opt_iso = self._execution_options.get("isolation_level", None) + return bool( + opt_iso == "AUTOCOMMIT" + or ( + opt_iso is None + and self.engine.dialect._on_connect_isolation_level + == "AUTOCOMMIT" + ) + ) + + def _get_required_transaction(self) -> RootTransaction: + trans = self._transaction + if trans is None: + raise exc.InvalidRequestError("connection is not in a transaction") + return trans + + def _get_required_nested_transaction(self) -> NestedTransaction: + trans = self._nested_transaction + if trans is None: + raise exc.InvalidRequestError( + "connection is not in a nested transaction" + ) + return trans + + def get_transaction(self) -> Optional[RootTransaction]: + """Return the current root transaction in progress, if any. + + .. versionadded:: 1.4 + + """ + + return self._transaction + + def get_nested_transaction(self) -> Optional[NestedTransaction]: + """Return the current nested transaction in progress, if any. + + .. versionadded:: 1.4 + + """ + return self._nested_transaction + + def _begin_impl(self, transaction: RootTransaction) -> None: + if self._echo: + if self._is_autocommit_isolation(): + self._log_info( + "BEGIN (implicit; DBAPI should not BEGIN due to " + "autocommit mode)" + ) + else: + self._log_info("BEGIN (implicit)") + + self.__in_begin = True + + if self._has_events or self.engine._has_events: + self.dispatch.begin(self) + + try: + self.engine.dialect.do_begin(self.connection) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + finally: + self.__in_begin = False + + def _rollback_impl(self) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.rollback(self) + + if self._still_open_and_dbapi_connection_is_valid: + if self._echo: + if self._is_autocommit_isolation(): + if self.dialect.skip_autocommit_rollback: + self._log_info( + "ROLLBACK will be skipped by " + "skip_autocommit_rollback" + ) + else: + self._log_info( + "ROLLBACK using DBAPI connection.rollback(); " + "set skip_autocommit_rollback to prevent fully" + ) + else: + self._log_info("ROLLBACK") + try: + self.engine.dialect.do_rollback(self.connection) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + def _commit_impl(self) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.commit(self) + + if self._echo: + if self._is_autocommit_isolation(): + self._log_info( + "COMMIT using DBAPI connection.commit(), " + "has no effect due to autocommit mode" + ) + else: + self._log_info("COMMIT") + try: + self.engine.dialect.do_commit(self.connection) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + def _savepoint_impl(self, name: Optional[str] = None) -> str: + if self._has_events or self.engine._has_events: + self.dispatch.savepoint(self, name) + + if name is None: + self.__savepoint_seq += 1 + name = "sa_savepoint_%s" % self.__savepoint_seq + self.engine.dialect.do_savepoint(self, name) + return name + + def _rollback_to_savepoint_impl(self, name: str) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.rollback_savepoint(self, name, None) + + if self._still_open_and_dbapi_connection_is_valid: + self.engine.dialect.do_rollback_to_savepoint(self, name) + + def _release_savepoint_impl(self, name: str) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.release_savepoint(self, name, None) + + self.engine.dialect.do_release_savepoint(self, name) + + def _begin_twophase_impl(self, transaction: TwoPhaseTransaction) -> None: + if self._echo: + self._log_info("BEGIN TWOPHASE (implicit)") + if self._has_events or self.engine._has_events: + self.dispatch.begin_twophase(self, transaction.xid) + + self.__in_begin = True + try: + self.engine.dialect.do_begin_twophase(self, transaction.xid) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + finally: + self.__in_begin = False + + def _prepare_twophase_impl(self, xid: Any) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.prepare_twophase(self, xid) + + assert isinstance(self._transaction, TwoPhaseTransaction) + try: + self.engine.dialect.do_prepare_twophase(self, xid) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + def _rollback_twophase_impl(self, xid: Any, is_prepared: bool) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.rollback_twophase(self, xid, is_prepared) + + if self._still_open_and_dbapi_connection_is_valid: + assert isinstance(self._transaction, TwoPhaseTransaction) + try: + self.engine.dialect.do_rollback_twophase( + self, xid, is_prepared + ) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + def _commit_twophase_impl(self, xid: Any, is_prepared: bool) -> None: + if self._has_events or self.engine._has_events: + self.dispatch.commit_twophase(self, xid, is_prepared) + + assert isinstance(self._transaction, TwoPhaseTransaction) + try: + self.engine.dialect.do_commit_twophase(self, xid, is_prepared) + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + def close(self) -> None: + """Close this :class:`_engine.Connection`. + + This results in a release of the underlying database + resources, that is, the DBAPI connection referenced + internally. The DBAPI connection is typically restored + back to the connection-holding :class:`_pool.Pool` referenced + by the :class:`_engine.Engine` that produced this + :class:`_engine.Connection`. Any transactional state present on + the DBAPI connection is also unconditionally released via + the DBAPI connection's ``rollback()`` method, regardless + of any :class:`.Transaction` object that may be + outstanding with regards to this :class:`_engine.Connection`. + + This has the effect of also calling :meth:`_engine.Connection.rollback` + if any transaction is in place. + + After :meth:`_engine.Connection.close` is called, the + :class:`_engine.Connection` is permanently in a closed state, + and will allow no further operations. + + """ + + if self._transaction: + self._transaction.close() + skip_reset = True + else: + skip_reset = False + + if self._dbapi_connection is not None: + conn = self._dbapi_connection + + # as we just closed the transaction, close the connection + # pool connection without doing an additional reset + if skip_reset: + cast("_ConnectionFairy", conn)._close_special( + transaction_reset=True + ) + else: + conn.close() + + # There is a slight chance that conn.close() may have + # triggered an invalidation here in which case + # _dbapi_connection would already be None, however usually + # it will be non-None here and in a "closed" state. + self._dbapi_connection = None + self.__can_reconnect = False + + @overload + def scalar( + self, + statement: TypedReturnsRows[Tuple[_T]], + parameters: Optional[_CoreSingleExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> Optional[_T]: ... + + @overload + def scalar( + self, + statement: Executable, + parameters: Optional[_CoreSingleExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> Any: ... + + def scalar( + self, + statement: Executable, + parameters: Optional[_CoreSingleExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> Any: + r"""Executes a SQL statement construct and returns a scalar object. + + This method is shorthand for invoking the + :meth:`_engine.Result.scalar` method after invoking the + :meth:`_engine.Connection.execute` method. Parameters are equivalent. + + :return: a scalar Python value representing the first column of the + first row returned. + + """ + distilled_parameters = _distill_params_20(parameters) + try: + meth = statement._execute_on_scalar + except AttributeError as err: + raise exc.ObjectNotExecutableError(statement) from err + else: + return meth( + self, + distilled_parameters, + execution_options or NO_OPTIONS, + ) + + @overload + def scalars( + self, + statement: TypedReturnsRows[Tuple[_T]], + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> ScalarResult[_T]: ... + + @overload + def scalars( + self, + statement: Executable, + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> ScalarResult[Any]: ... + + def scalars( + self, + statement: Executable, + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> ScalarResult[Any]: + """Executes and returns a scalar result set, which yields scalar values + from the first column of each row. + + This method is equivalent to calling :meth:`_engine.Connection.execute` + to receive a :class:`_result.Result` object, then invoking the + :meth:`_result.Result.scalars` method to produce a + :class:`_result.ScalarResult` instance. + + :return: a :class:`_result.ScalarResult` + + .. versionadded:: 1.4.24 + + """ + + return self.execute( + statement, parameters, execution_options=execution_options + ).scalars() + + @overload + def execute( + self, + statement: TypedReturnsRows[_T], + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> CursorResult[_T]: ... + + @overload + def execute( + self, + statement: Executable, + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> CursorResult[Any]: ... + + def execute( + self, + statement: Executable, + parameters: Optional[_CoreAnyExecuteParams] = None, + *, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> CursorResult[Any]: + r"""Executes a SQL statement construct and returns a + :class:`_engine.CursorResult`. + + :param statement: The statement to be executed. This is always + an object that is in both the :class:`_expression.ClauseElement` and + :class:`_expression.Executable` hierarchies, including: + + * :class:`_expression.Select` + * :class:`_expression.Insert`, :class:`_expression.Update`, + :class:`_expression.Delete` + * :class:`_expression.TextClause` and + :class:`_expression.TextualSelect` + * :class:`_schema.DDL` and objects which inherit from + :class:`_schema.ExecutableDDLElement` + + :param parameters: parameters which will be bound into the statement. + This may be either a dictionary of parameter names to values, + or a mutable sequence (e.g. a list) of dictionaries. When a + list of dictionaries is passed, the underlying statement execution + will make use of the DBAPI ``cursor.executemany()`` method. + When a single dictionary is passed, the DBAPI ``cursor.execute()`` + method will be used. + + :param execution_options: optional dictionary of execution options, + which will be associated with the statement execution. This + dictionary can provide a subset of the options that are accepted + by :meth:`_engine.Connection.execution_options`. + + :return: a :class:`_engine.Result` object. + + """ + distilled_parameters = _distill_params_20(parameters) + try: + meth = statement._execute_on_connection + except AttributeError as err: + raise exc.ObjectNotExecutableError(statement) from err + else: + return meth( + self, + distilled_parameters, + execution_options or NO_OPTIONS, + ) + + def _execute_function( + self, + func: FunctionElement[Any], + distilled_parameters: _CoreMultiExecuteParams, + execution_options: CoreExecuteOptionsParameter, + ) -> CursorResult[Any]: + """Execute a sql.FunctionElement object.""" + + return self._execute_clauseelement( + func.select(), distilled_parameters, execution_options + ) + + def _execute_default( + self, + default: DefaultGenerator, + distilled_parameters: _CoreMultiExecuteParams, + execution_options: CoreExecuteOptionsParameter, + ) -> Any: + """Execute a schema.ColumnDefault object.""" + + execution_options = self._execution_options.merge_with( + execution_options + ) + + event_multiparams: Optional[_CoreMultiExecuteParams] + event_params: Optional[_CoreAnyExecuteParams] + + # note for event handlers, the "distilled parameters" which is always + # a list of dicts is broken out into separate "multiparams" and + # "params" collections, which allows the handler to distinguish + # between an executemany and execute style set of parameters. + if self._has_events or self.engine._has_events: + ( + default, + distilled_parameters, + event_multiparams, + event_params, + ) = self._invoke_before_exec_event( + default, distilled_parameters, execution_options + ) + else: + event_multiparams = event_params = None + + try: + conn = self._dbapi_connection + if conn is None: + conn = self._revalidate_connection() + + dialect = self.dialect + ctx = dialect.execution_ctx_cls._init_default( + dialect, self, conn, execution_options + ) + except (exc.PendingRollbackError, exc.ResourceClosedError): + raise + except BaseException as e: + self._handle_dbapi_exception(e, None, None, None, None) + + ret = ctx._exec_default(None, default, None) + + if self._has_events or self.engine._has_events: + self.dispatch.after_execute( + self, + default, + event_multiparams, + event_params, + execution_options, + ret, + ) + + return ret + + def _execute_ddl( + self, + ddl: ExecutableDDLElement, + distilled_parameters: _CoreMultiExecuteParams, + execution_options: CoreExecuteOptionsParameter, + ) -> CursorResult[Any]: + """Execute a schema.DDL object.""" + + exec_opts = ddl._execution_options.merge_with( + self._execution_options, execution_options + ) + + event_multiparams: Optional[_CoreMultiExecuteParams] + event_params: Optional[_CoreSingleExecuteParams] + + if self._has_events or self.engine._has_events: + ( + ddl, + distilled_parameters, + event_multiparams, + event_params, + ) = self._invoke_before_exec_event( + ddl, distilled_parameters, exec_opts + ) + else: + event_multiparams = event_params = None + + schema_translate_map = exec_opts.get("schema_translate_map", None) + + dialect = self.dialect + + compiled = ddl.compile( + dialect=dialect, schema_translate_map=schema_translate_map + ) + ret = self._execute_context( + dialect, + dialect.execution_ctx_cls._init_ddl, + compiled, + None, + exec_opts, + compiled, + ) + if self._has_events or self.engine._has_events: + self.dispatch.after_execute( + self, + ddl, + event_multiparams, + event_params, + exec_opts, + ret, + ) + return ret + + def _invoke_before_exec_event( + self, + elem: Any, + distilled_params: _CoreMultiExecuteParams, + execution_options: _ExecuteOptions, + ) -> Tuple[ + Any, + _CoreMultiExecuteParams, + _CoreMultiExecuteParams, + _CoreSingleExecuteParams, + ]: + event_multiparams: _CoreMultiExecuteParams + event_params: _CoreSingleExecuteParams + + if len(distilled_params) == 1: + event_multiparams, event_params = [], distilled_params[0] + else: + event_multiparams, event_params = distilled_params, {} + + for fn in self.dispatch.before_execute: + elem, event_multiparams, event_params = fn( + self, + elem, + event_multiparams, + event_params, + execution_options, + ) + + if event_multiparams: + distilled_params = list(event_multiparams) + if event_params: + raise exc.InvalidRequestError( + "Event handler can't return non-empty multiparams " + "and params at the same time" + ) + elif event_params: + distilled_params = [event_params] + else: + distilled_params = [] + + return elem, distilled_params, event_multiparams, event_params + + def _execute_clauseelement( + self, + elem: Executable, + distilled_parameters: _CoreMultiExecuteParams, + execution_options: CoreExecuteOptionsParameter, + ) -> CursorResult[Any]: + """Execute a sql.ClauseElement object.""" + + execution_options = elem._execution_options.merge_with( + self._execution_options, execution_options + ) + + has_events = self._has_events or self.engine._has_events + if has_events: + ( + elem, + distilled_parameters, + event_multiparams, + event_params, + ) = self._invoke_before_exec_event( + elem, distilled_parameters, execution_options + ) + + if distilled_parameters: + # ensure we don't retain a link to the view object for keys() + # which links to the values, which we don't want to cache + keys = sorted(distilled_parameters[0]) + for_executemany = len(distilled_parameters) > 1 + else: + keys = [] + for_executemany = False + + dialect = self.dialect + + schema_translate_map = execution_options.get( + "schema_translate_map", None + ) + + compiled_cache: Optional[CompiledCacheType] = execution_options.get( + "compiled_cache", self.engine._compiled_cache + ) + + compiled_sql, extracted_params, cache_hit = elem._compile_w_cache( + dialect=dialect, + compiled_cache=compiled_cache, + column_keys=keys, + for_executemany=for_executemany, + schema_translate_map=schema_translate_map, + linting=self.dialect.compiler_linting | compiler.WARN_LINTING, + ) + ret = self._execute_context( + dialect, + dialect.execution_ctx_cls._init_compiled, + compiled_sql, + distilled_parameters, + execution_options, + compiled_sql, + distilled_parameters, + elem, + extracted_params, + cache_hit=cache_hit, + ) + if has_events: + self.dispatch.after_execute( + self, + elem, + event_multiparams, + event_params, + execution_options, + ret, + ) + return ret + + def _execute_compiled( + self, + compiled: Compiled, + distilled_parameters: _CoreMultiExecuteParams, + execution_options: CoreExecuteOptionsParameter = _EMPTY_EXECUTION_OPTS, + ) -> CursorResult[Any]: + """Execute a sql.Compiled object. + + TODO: why do we have this? likely deprecate or remove + + """ + + execution_options = compiled.execution_options.merge_with( + self._execution_options, execution_options + ) + + if self._has_events or self.engine._has_events: + ( + compiled, + distilled_parameters, + event_multiparams, + event_params, + ) = self._invoke_before_exec_event( + compiled, distilled_parameters, execution_options + ) + + dialect = self.dialect + + ret = self._execute_context( + dialect, + dialect.execution_ctx_cls._init_compiled, + compiled, + distilled_parameters, + execution_options, + compiled, + distilled_parameters, + None, + None, + ) + if self._has_events or self.engine._has_events: + self.dispatch.after_execute( + self, + compiled, + event_multiparams, + event_params, + execution_options, + ret, + ) + return ret + + def exec_driver_sql( + self, + statement: str, + parameters: Optional[_DBAPIAnyExecuteParams] = None, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> CursorResult[Any]: + r"""Executes a string SQL statement on the DBAPI cursor directly, + without any SQL compilation steps. + + This can be used to pass any string directly to the + ``cursor.execute()`` method of the DBAPI in use. + + :param statement: The statement str to be executed. Bound parameters + must use the underlying DBAPI's paramstyle, such as "qmark", + "pyformat", "format", etc. + + :param parameters: represent bound parameter values to be used in the + execution. The format is one of: a dictionary of named parameters, + a tuple of positional parameters, or a list containing either + dictionaries or tuples for multiple-execute support. + + :return: a :class:`_engine.CursorResult`. + + E.g. multiple dictionaries:: + + + conn.exec_driver_sql( + "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", + [{"id": 1, "value": "v1"}, {"id": 2, "value": "v2"}], + ) + + Single dictionary:: + + conn.exec_driver_sql( + "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", + dict(id=1, value="v1"), + ) + + Single tuple:: + + conn.exec_driver_sql( + "INSERT INTO table (id, value) VALUES (?, ?)", (1, "v1") + ) + + .. note:: The :meth:`_engine.Connection.exec_driver_sql` method does + not participate in the + :meth:`_events.ConnectionEvents.before_execute` and + :meth:`_events.ConnectionEvents.after_execute` events. To + intercept calls to :meth:`_engine.Connection.exec_driver_sql`, use + :meth:`_events.ConnectionEvents.before_cursor_execute` and + :meth:`_events.ConnectionEvents.after_cursor_execute`. + + .. seealso:: + + :pep:`249` + + """ + + distilled_parameters = _distill_raw_params(parameters) + + execution_options = self._execution_options.merge_with( + execution_options + ) + + dialect = self.dialect + ret = self._execute_context( + dialect, + dialect.execution_ctx_cls._init_statement, + statement, + None, + execution_options, + statement, + distilled_parameters, + ) + + return ret + + def _execute_context( + self, + dialect: Dialect, + constructor: Callable[..., ExecutionContext], + statement: Union[str, Compiled], + parameters: Optional[_AnyMultiExecuteParams], + execution_options: _ExecuteOptions, + *args: Any, + **kw: Any, + ) -> CursorResult[Any]: + """Create an :class:`.ExecutionContext` and execute, returning + a :class:`_engine.CursorResult`.""" + + if execution_options: + yp = execution_options.get("yield_per", None) + if yp: + execution_options = execution_options.union( + {"stream_results": True, "max_row_buffer": yp} + ) + try: + conn = self._dbapi_connection + if conn is None: + conn = self._revalidate_connection() + + context = constructor( + dialect, self, conn, execution_options, *args, **kw + ) + except (exc.PendingRollbackError, exc.ResourceClosedError): + raise + except BaseException as e: + self._handle_dbapi_exception( + e, str(statement), parameters, None, None + ) + + if ( + self._transaction + and not self._transaction.is_active + or ( + self._nested_transaction + and not self._nested_transaction.is_active + ) + ): + self._invalid_transaction() + + elif self._trans_context_manager: + TransactionalContext._trans_ctx_check(self) + + if self._transaction is None: + self._autobegin() + + context.pre_exec() + + if context.execute_style is ExecuteStyle.INSERTMANYVALUES: + return self._exec_insertmany_context(dialect, context) + else: + return self._exec_single_context( + dialect, context, statement, parameters + ) + + def _exec_single_context( + self, + dialect: Dialect, + context: ExecutionContext, + statement: Union[str, Compiled], + parameters: Optional[_AnyMultiExecuteParams], + ) -> CursorResult[Any]: + """continue the _execute_context() method for a single DBAPI + cursor.execute() or cursor.executemany() call. + + """ + if dialect.bind_typing is BindTyping.SETINPUTSIZES: + generic_setinputsizes = context._prepare_set_input_sizes() + + if generic_setinputsizes: + try: + dialect.do_set_input_sizes( + context.cursor, generic_setinputsizes, context + ) + except BaseException as e: + self._handle_dbapi_exception( + e, str(statement), parameters, None, context + ) + + cursor, str_statement, parameters = ( + context.cursor, + context.statement, + context.parameters, + ) + + effective_parameters: Optional[_AnyExecuteParams] + + if not context.executemany: + effective_parameters = parameters[0] + else: + effective_parameters = parameters + + if self._has_events or self.engine._has_events: + for fn in self.dispatch.before_cursor_execute: + str_statement, effective_parameters = fn( + self, + cursor, + str_statement, + effective_parameters, + context, + context.executemany, + ) + + if self._echo: + self._log_info(str_statement) + + stats = context._get_cache_stats() + + if not self.engine.hide_parameters: + self._log_info( + "[%s] %r", + stats, + sql_util._repr_params( + effective_parameters, + batches=10, + ismulti=context.executemany, + ), + ) + else: + self._log_info( + "[%s] [SQL parameters hidden due to hide_parameters=True]", + stats, + ) + + evt_handled: bool = False + try: + if context.execute_style is ExecuteStyle.EXECUTEMANY: + effective_parameters = cast( + "_CoreMultiExecuteParams", effective_parameters + ) + if self.dialect._has_events: + for fn in self.dialect.dispatch.do_executemany: + if fn( + cursor, + str_statement, + effective_parameters, + context, + ): + evt_handled = True + break + if not evt_handled: + self.dialect.do_executemany( + cursor, + str_statement, + effective_parameters, + context, + ) + elif not effective_parameters and context.no_parameters: + if self.dialect._has_events: + for fn in self.dialect.dispatch.do_execute_no_params: + if fn(cursor, str_statement, context): + evt_handled = True + break + if not evt_handled: + self.dialect.do_execute_no_params( + cursor, str_statement, context + ) + else: + effective_parameters = cast( + "_CoreSingleExecuteParams", effective_parameters + ) + if self.dialect._has_events: + for fn in self.dialect.dispatch.do_execute: + if fn( + cursor, + str_statement, + effective_parameters, + context, + ): + evt_handled = True + break + if not evt_handled: + self.dialect.do_execute( + cursor, str_statement, effective_parameters, context + ) + + if self._has_events or self.engine._has_events: + self.dispatch.after_cursor_execute( + self, + cursor, + str_statement, + effective_parameters, + context, + context.executemany, + ) + + context.post_exec() + + result = context._setup_result_proxy() + + except BaseException as e: + self._handle_dbapi_exception( + e, str_statement, effective_parameters, cursor, context + ) + + return result + + def _exec_insertmany_context( + self, + dialect: Dialect, + context: ExecutionContext, + ) -> CursorResult[Any]: + """continue the _execute_context() method for an "insertmanyvalues" + operation, which will invoke DBAPI + cursor.execute() one or more times with individual log and + event hook calls. + + """ + + if dialect.bind_typing is BindTyping.SETINPUTSIZES: + generic_setinputsizes = context._prepare_set_input_sizes() + else: + generic_setinputsizes = None + + cursor, str_statement, parameters = ( + context.cursor, + context.statement, + context.parameters, + ) + + effective_parameters = parameters + + engine_events = self._has_events or self.engine._has_events + if self.dialect._has_events: + do_execute_dispatch: Iterable[Any] = ( + self.dialect.dispatch.do_execute + ) + else: + do_execute_dispatch = () + + if engine_events: + _WORKAROUND_ISSUE_13018 = getattr( + self, "_WORKAROUND_ISSUE_13018", False + ) + else: + _WORKAROUND_ISSUE_13018 = False + + if self._echo: + stats = context._get_cache_stats() + " (insertmanyvalues)" + + preserve_rowcount = context.execution_options.get( + "preserve_rowcount", False + ) + rowcount = 0 + + for imv_batch in dialect._deliver_insertmanyvalues_batches( + self, + cursor, + str_statement, + effective_parameters, + generic_setinputsizes, + context, + ): + if imv_batch.processed_setinputsizes: + try: + dialect.do_set_input_sizes( + context.cursor, + imv_batch.processed_setinputsizes, + context, + ) + except BaseException as e: + self._handle_dbapi_exception( + e, + sql_util._long_statement(imv_batch.replaced_statement), + imv_batch.replaced_parameters, + None, + context, + is_sub_exec=True, + ) + + sub_stmt = imv_batch.replaced_statement + sub_params = imv_batch.replaced_parameters + + if engine_events: + for fn in self.dispatch.before_cursor_execute: + sub_stmt, sub_params = fn( + self, + cursor, + sub_stmt, + sub_params, + context, + True, + ) + + if self._echo: + self._log_info(sql_util._long_statement(sub_stmt)) + + imv_stats = f""" {imv_batch.batchnum}/{ + imv_batch.total_batches + } ({ + 'ordered' + if imv_batch.rows_sorted else 'unordered' + }{ + '; batch not supported' + if imv_batch.is_downgraded + else '' + })""" + + if imv_batch.batchnum == 1: + stats += imv_stats + else: + stats = f"insertmanyvalues{imv_stats}" + + if not self.engine.hide_parameters: + self._log_info( + "[%s] %r", + stats, + sql_util._repr_params( + sub_params, + batches=10, + ismulti=False, + ), + ) + else: + self._log_info( + "[%s] [SQL parameters hidden due to " + "hide_parameters=True]", + stats, + ) + + try: + for fn in do_execute_dispatch: + if fn( + cursor, + sub_stmt, + sub_params, + context, + ): + break + else: + dialect.do_execute( + cursor, + sub_stmt, + sub_params, + context, + ) + + except BaseException as e: + self._handle_dbapi_exception( + e, + sql_util._long_statement(sub_stmt), + sub_params, + cursor, + context, + is_sub_exec=True, + ) + + if engine_events: + self.dispatch.after_cursor_execute( + self, + cursor, + # TODO: this will be fixed by #13018 + sub_stmt if _WORKAROUND_ISSUE_13018 else str_statement, + sub_params if _WORKAROUND_ISSUE_13018 else parameters, + context, + context.executemany, + ) + + if preserve_rowcount: + rowcount += imv_batch.current_batch_size + + try: + context.post_exec() + + if preserve_rowcount: + context._rowcount = rowcount # type: ignore[attr-defined] + + result = context._setup_result_proxy() + + except BaseException as e: + self._handle_dbapi_exception( + e, str_statement, effective_parameters, cursor, context + ) + + return result + + def _cursor_execute( + self, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPISingleExecuteParams, + context: Optional[ExecutionContext] = None, + ) -> None: + """Execute a statement + params on the given cursor. + + Adds appropriate logging and exception handling. + + This method is used by DefaultDialect for special-case + executions, such as for sequences and column defaults. + The path of statement execution in the majority of cases + terminates at _execute_context(). + + """ + if self._has_events or self.engine._has_events: + for fn in self.dispatch.before_cursor_execute: + statement, parameters = fn( + self, cursor, statement, parameters, context, False + ) + + if self._echo: + self._log_info(statement) + self._log_info("[raw sql] %r", parameters) + try: + for fn in ( + () + if not self.dialect._has_events + else self.dialect.dispatch.do_execute + ): + if fn(cursor, statement, parameters, context): + break + else: + self.dialect.do_execute(cursor, statement, parameters, context) + except BaseException as e: + self._handle_dbapi_exception( + e, statement, parameters, cursor, context + ) + + if self._has_events or self.engine._has_events: + self.dispatch.after_cursor_execute( + self, cursor, statement, parameters, context, False + ) + + def _safe_close_cursor(self, cursor: DBAPICursor) -> None: + """Close the given cursor, catching exceptions + and turning into log warnings. + + """ + try: + cursor.close() + except Exception: + # log the error through the connection pool's logger. + self.engine.pool.logger.error( + "Error closing cursor", exc_info=True + ) + + _reentrant_error = False + _is_disconnect = False + + def _handle_dbapi_exception( + self, + e: BaseException, + statement: Optional[str], + parameters: Optional[_AnyExecuteParams], + cursor: Optional[DBAPICursor], + context: Optional[ExecutionContext], + is_sub_exec: bool = False, + ) -> NoReturn: + exc_info = sys.exc_info() + + is_exit_exception = util.is_exit_exception(e) + + if not self._is_disconnect: + self._is_disconnect = ( + isinstance(e, self.dialect.loaded_dbapi.Error) + and not self.closed + and self.dialect.is_disconnect( + e, + self._dbapi_connection if not self.invalidated else None, + cursor, + ) + ) or (is_exit_exception and not self.closed) + + invalidate_pool_on_disconnect = not is_exit_exception + + ismulti: bool = ( + not is_sub_exec and context.executemany + if context is not None + else False + ) + if self._reentrant_error: + raise exc.DBAPIError.instance( + statement, + parameters, + e, + self.dialect.loaded_dbapi.Error, + hide_parameters=self.engine.hide_parameters, + dialect=self.dialect, + ismulti=ismulti, + ).with_traceback(exc_info[2]) from e + self._reentrant_error = True + try: + # non-DBAPI error - if we already got a context, + # or there's no string statement, don't wrap it + should_wrap = isinstance(e, self.dialect.loaded_dbapi.Error) or ( + statement is not None + and context is None + and not is_exit_exception + ) + + if should_wrap: + sqlalchemy_exception = exc.DBAPIError.instance( + statement, + parameters, + cast(Exception, e), + self.dialect.loaded_dbapi.Error, + hide_parameters=self.engine.hide_parameters, + connection_invalidated=self._is_disconnect, + dialect=self.dialect, + ismulti=ismulti, + ) + else: + sqlalchemy_exception = None + + newraise = None + + if (self.dialect._has_events) and not self._execution_options.get( + "skip_user_error_events", False + ): + ctx = ExceptionContextImpl( + e, + sqlalchemy_exception, + self.engine, + self.dialect, + self, + cursor, + statement, + parameters, + context, + self._is_disconnect, + invalidate_pool_on_disconnect, + False, + ) + + for fn in self.dialect.dispatch.handle_error: + try: + # handler returns an exception; + # call next handler in a chain + per_fn = fn(ctx) + if per_fn is not None: + ctx.chained_exception = newraise = per_fn + except Exception as _raised: + # handler raises an exception - stop processing + newraise = _raised + break + + if self._is_disconnect != ctx.is_disconnect: + self._is_disconnect = ctx.is_disconnect + if sqlalchemy_exception: + sqlalchemy_exception.connection_invalidated = ( + ctx.is_disconnect + ) + + # set up potentially user-defined value for + # invalidate pool. + invalidate_pool_on_disconnect = ( + ctx.invalidate_pool_on_disconnect + ) + + if should_wrap and context: + context.handle_dbapi_exception(e) + + if not self._is_disconnect: + if cursor: + self._safe_close_cursor(cursor) + # "autorollback" was mostly relevant in 1.x series. + # It's very unlikely to reach here, as the connection + # does autobegin so when we are here, we are usually + # in an explicit / semi-explicit transaction. + # however we have a test which manufactures this + # scenario in any case using an event handler. + # test/engine/test_execute.py-> test_actual_autorollback + if not self.in_transaction(): + self._rollback_impl() + + if newraise: + raise newraise.with_traceback(exc_info[2]) from e + elif should_wrap: + assert sqlalchemy_exception is not None + raise sqlalchemy_exception.with_traceback(exc_info[2]) from e + else: + assert exc_info[1] is not None + raise exc_info[1].with_traceback(exc_info[2]) + finally: + del self._reentrant_error + if self._is_disconnect: + del self._is_disconnect + if not self.invalidated: + dbapi_conn_wrapper = self._dbapi_connection + assert dbapi_conn_wrapper is not None + if invalidate_pool_on_disconnect: + self.engine.pool._invalidate(dbapi_conn_wrapper, e) + self.invalidate(e) + + @classmethod + def _handle_dbapi_exception_noconnection( + cls, + e: BaseException, + dialect: Dialect, + engine: Optional[Engine] = None, + is_disconnect: Optional[bool] = None, + invalidate_pool_on_disconnect: bool = True, + is_pre_ping: bool = False, + ) -> NoReturn: + exc_info = sys.exc_info() + + if is_disconnect is None: + is_disconnect = isinstance( + e, dialect.loaded_dbapi.Error + ) and dialect.is_disconnect(e, None, None) + + should_wrap = isinstance(e, dialect.loaded_dbapi.Error) + + if should_wrap: + sqlalchemy_exception = exc.DBAPIError.instance( + None, + None, + cast(Exception, e), + dialect.loaded_dbapi.Error, + hide_parameters=( + engine.hide_parameters if engine is not None else False + ), + connection_invalidated=is_disconnect, + dialect=dialect, + ) + else: + sqlalchemy_exception = None + + newraise = None + + if dialect._has_events: + ctx = ExceptionContextImpl( + e, + sqlalchemy_exception, + engine, + dialect, + None, + None, + None, + None, + None, + is_disconnect, + invalidate_pool_on_disconnect, + is_pre_ping, + ) + for fn in dialect.dispatch.handle_error: + try: + # handler returns an exception; + # call next handler in a chain + per_fn = fn(ctx) + if per_fn is not None: + ctx.chained_exception = newraise = per_fn + except Exception as _raised: + # handler raises an exception - stop processing + newraise = _raised + break + + if sqlalchemy_exception and is_disconnect != ctx.is_disconnect: + sqlalchemy_exception.connection_invalidated = ctx.is_disconnect + + if newraise: + raise newraise.with_traceback(exc_info[2]) from e + elif should_wrap: + assert sqlalchemy_exception is not None + raise sqlalchemy_exception.with_traceback(exc_info[2]) from e + else: + assert exc_info[1] is not None + raise exc_info[1].with_traceback(exc_info[2]) + + def _run_ddl_visitor( + self, + visitorcallable: Type[InvokeDDLBase], + element: SchemaVisitable, + **kwargs: Any, + ) -> None: + """run a DDL visitor. + + This method is only here so that the MockConnection can change the + options given to the visitor so that "checkfirst" is skipped. + + """ + visitorcallable( + dialect=self.dialect, connection=self, **kwargs + ).traverse_single(element) + + +class ExceptionContextImpl(ExceptionContext): + """Implement the :class:`.ExceptionContext` interface.""" + + __slots__ = ( + "connection", + "engine", + "dialect", + "cursor", + "statement", + "parameters", + "original_exception", + "sqlalchemy_exception", + "chained_exception", + "execution_context", + "is_disconnect", + "invalidate_pool_on_disconnect", + "is_pre_ping", + ) + + def __init__( + self, + exception: BaseException, + sqlalchemy_exception: Optional[exc.StatementError], + engine: Optional[Engine], + dialect: Dialect, + connection: Optional[Connection], + cursor: Optional[DBAPICursor], + statement: Optional[str], + parameters: Optional[_DBAPIAnyExecuteParams], + context: Optional[ExecutionContext], + is_disconnect: bool, + invalidate_pool_on_disconnect: bool, + is_pre_ping: bool, + ): + self.engine = engine + self.dialect = dialect + self.connection = connection + self.sqlalchemy_exception = sqlalchemy_exception + self.original_exception = exception + self.execution_context = context + self.statement = statement + self.parameters = parameters + self.is_disconnect = is_disconnect + self.invalidate_pool_on_disconnect = invalidate_pool_on_disconnect + self.is_pre_ping = is_pre_ping + + +class Transaction(TransactionalContext): + """Represent a database transaction in progress. + + The :class:`.Transaction` object is procured by + calling the :meth:`_engine.Connection.begin` method of + :class:`_engine.Connection`:: + + from sqlalchemy import create_engine + + engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") + connection = engine.connect() + trans = connection.begin() + connection.execute(text("insert into x (a, b) values (1, 2)")) + trans.commit() + + The object provides :meth:`.rollback` and :meth:`.commit` + methods in order to control transaction boundaries. It + also implements a context manager interface so that + the Python ``with`` statement can be used with the + :meth:`_engine.Connection.begin` method:: + + with connection.begin(): + connection.execute(text("insert into x (a, b) values (1, 2)")) + + The Transaction object is **not** threadsafe. + + .. seealso:: + + :meth:`_engine.Connection.begin` + + :meth:`_engine.Connection.begin_twophase` + + :meth:`_engine.Connection.begin_nested` + + .. index:: + single: thread safety; Transaction + """ # noqa + + __slots__ = () + + _is_root: bool = False + is_active: bool + connection: Connection + + def __init__(self, connection: Connection): + raise NotImplementedError() + + @property + def _deactivated_from_connection(self) -> bool: + """True if this transaction is totally deactivated from the connection + and therefore can no longer affect its state. + + """ + raise NotImplementedError() + + def _do_close(self) -> None: + raise NotImplementedError() + + def _do_rollback(self) -> None: + raise NotImplementedError() + + def _do_commit(self) -> None: + raise NotImplementedError() + + @property + def is_valid(self) -> bool: + return self.is_active and not self.connection.invalidated + + def close(self) -> None: + """Close this :class:`.Transaction`. + + If this transaction is the base transaction in a begin/commit + nesting, the transaction will rollback(). Otherwise, the + method returns. + + This is used to cancel a Transaction without affecting the scope of + an enclosing transaction. + + """ + try: + self._do_close() + finally: + assert not self.is_active + + def rollback(self) -> None: + """Roll back this :class:`.Transaction`. + + The implementation of this may vary based on the type of transaction in + use: + + * For a simple database transaction (e.g. :class:`.RootTransaction`), + it corresponds to a ROLLBACK. + + * For a :class:`.NestedTransaction`, it corresponds to a + "ROLLBACK TO SAVEPOINT" operation. + + * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two + phase transactions may be used. + + + """ + try: + self._do_rollback() + finally: + assert not self.is_active + + def commit(self) -> None: + """Commit this :class:`.Transaction`. + + The implementation of this may vary based on the type of transaction in + use: + + * For a simple database transaction (e.g. :class:`.RootTransaction`), + it corresponds to a COMMIT. + + * For a :class:`.NestedTransaction`, it corresponds to a + "RELEASE SAVEPOINT" operation. + + * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two + phase transactions may be used. + + """ + try: + self._do_commit() + finally: + assert not self.is_active + + def _get_subject(self) -> Connection: + return self.connection + + def _transaction_is_active(self) -> bool: + return self.is_active + + def _transaction_is_closed(self) -> bool: + return not self._deactivated_from_connection + + def _rollback_can_be_called(self) -> bool: + # for RootTransaction / NestedTransaction, it's safe to call + # rollback() even if the transaction is deactive and no warnings + # will be emitted. tested in + # test_transaction.py -> test_no_rollback_in_deactive(?:_savepoint)? + return True + + +class RootTransaction(Transaction): + """Represent the "root" transaction on a :class:`_engine.Connection`. + + This corresponds to the current "BEGIN/COMMIT/ROLLBACK" that's occurring + for the :class:`_engine.Connection`. The :class:`_engine.RootTransaction` + is created by calling upon the :meth:`_engine.Connection.begin` method, and + remains associated with the :class:`_engine.Connection` throughout its + active span. The current :class:`_engine.RootTransaction` in use is + accessible via the :attr:`_engine.Connection.get_transaction` method of + :class:`_engine.Connection`. + + In :term:`2.0 style` use, the :class:`_engine.Connection` also employs + "autobegin" behavior that will create a new + :class:`_engine.RootTransaction` whenever a connection in a + non-transactional state is used to emit commands on the DBAPI connection. + The scope of the :class:`_engine.RootTransaction` in 2.0 style + use can be controlled using the :meth:`_engine.Connection.commit` and + :meth:`_engine.Connection.rollback` methods. + + + """ + + _is_root = True + + __slots__ = ("connection", "is_active") + + def __init__(self, connection: Connection): + assert connection._transaction is None + if connection._trans_context_manager: + TransactionalContext._trans_ctx_check(connection) + self.connection = connection + self._connection_begin_impl() + connection._transaction = self + + self.is_active = True + + def _deactivate_from_connection(self) -> None: + if self.is_active: + assert self.connection._transaction is self + self.is_active = False + + elif self.connection._transaction is not self: + util.warn("transaction already deassociated from connection") + + @property + def _deactivated_from_connection(self) -> bool: + return self.connection._transaction is not self + + def _connection_begin_impl(self) -> None: + self.connection._begin_impl(self) + + def _connection_rollback_impl(self) -> None: + self.connection._rollback_impl() + + def _connection_commit_impl(self) -> None: + self.connection._commit_impl() + + def _close_impl(self, try_deactivate: bool = False) -> None: + try: + if self.is_active: + self._connection_rollback_impl() + + if self.connection._nested_transaction: + self.connection._nested_transaction._cancel() + finally: + if self.is_active or try_deactivate: + self._deactivate_from_connection() + if self.connection._transaction is self: + self.connection._transaction = None + + assert not self.is_active + assert self.connection._transaction is not self + + def _do_close(self) -> None: + self._close_impl() + + def _do_rollback(self) -> None: + self._close_impl(try_deactivate=True) + + def _do_commit(self) -> None: + if self.is_active: + assert self.connection._transaction is self + + try: + self._connection_commit_impl() + finally: + # whether or not commit succeeds, cancel any + # nested transactions, make this transaction "inactive" + # and remove it as a reset agent + if self.connection._nested_transaction: + self.connection._nested_transaction._cancel() + + self._deactivate_from_connection() + + # ...however only remove as the connection's current transaction + # if commit succeeded. otherwise it stays on so that a rollback + # needs to occur. + self.connection._transaction = None + else: + if self.connection._transaction is self: + self.connection._invalid_transaction() + else: + raise exc.InvalidRequestError("This transaction is inactive") + + assert not self.is_active + assert self.connection._transaction is not self + + +class NestedTransaction(Transaction): + """Represent a 'nested', or SAVEPOINT transaction. + + The :class:`.NestedTransaction` object is created by calling the + :meth:`_engine.Connection.begin_nested` method of + :class:`_engine.Connection`. + + When using :class:`.NestedTransaction`, the semantics of "begin" / + "commit" / "rollback" are as follows: + + * the "begin" operation corresponds to the "BEGIN SAVEPOINT" command, where + the savepoint is given an explicit name that is part of the state + of this object. + + * The :meth:`.NestedTransaction.commit` method corresponds to a + "RELEASE SAVEPOINT" operation, using the savepoint identifier associated + with this :class:`.NestedTransaction`. + + * The :meth:`.NestedTransaction.rollback` method corresponds to a + "ROLLBACK TO SAVEPOINT" operation, using the savepoint identifier + associated with this :class:`.NestedTransaction`. + + The rationale for mimicking the semantics of an outer transaction in + terms of savepoints so that code may deal with a "savepoint" transaction + and an "outer" transaction in an agnostic way. + + .. seealso:: + + :ref:`session_begin_nested` - ORM version of the SAVEPOINT API. + + """ + + __slots__ = ("connection", "is_active", "_savepoint", "_previous_nested") + + _savepoint: str + + def __init__(self, connection: Connection): + assert connection._transaction is not None + if connection._trans_context_manager: + TransactionalContext._trans_ctx_check(connection) + self.connection = connection + self._savepoint = self.connection._savepoint_impl() + self.is_active = True + self._previous_nested = connection._nested_transaction + connection._nested_transaction = self + + def _deactivate_from_connection(self, warn: bool = True) -> None: + if self.connection._nested_transaction is self: + self.connection._nested_transaction = self._previous_nested + elif warn: + util.warn( + "nested transaction already deassociated from connection" + ) + + @property + def _deactivated_from_connection(self) -> bool: + return self.connection._nested_transaction is not self + + def _cancel(self) -> None: + # called by RootTransaction when the outer transaction is + # committed, rolled back, or closed to cancel all savepoints + # without any action being taken + self.is_active = False + self._deactivate_from_connection() + if self._previous_nested: + self._previous_nested._cancel() + + def _close_impl( + self, deactivate_from_connection: bool, warn_already_deactive: bool + ) -> None: + try: + if ( + self.is_active + and self.connection._transaction + and self.connection._transaction.is_active + ): + self.connection._rollback_to_savepoint_impl(self._savepoint) + finally: + self.is_active = False + + if deactivate_from_connection: + self._deactivate_from_connection(warn=warn_already_deactive) + + assert not self.is_active + if deactivate_from_connection: + assert self.connection._nested_transaction is not self + + def _do_close(self) -> None: + self._close_impl(True, False) + + def _do_rollback(self) -> None: + self._close_impl(True, True) + + def _do_commit(self) -> None: + if self.is_active: + try: + self.connection._release_savepoint_impl(self._savepoint) + finally: + # nested trans becomes inactive on failed release + # unconditionally. this prevents it from trying to + # emit SQL when it rolls back. + self.is_active = False + + # but only de-associate from connection if it succeeded + self._deactivate_from_connection() + else: + if self.connection._nested_transaction is self: + self.connection._invalid_transaction() + else: + raise exc.InvalidRequestError( + "This nested transaction is inactive" + ) + + +class TwoPhaseTransaction(RootTransaction): + """Represent a two-phase transaction. + + A new :class:`.TwoPhaseTransaction` object may be procured + using the :meth:`_engine.Connection.begin_twophase` method. + + The interface is the same as that of :class:`.Transaction` + with the addition of the :meth:`prepare` method. + + """ + + __slots__ = ("xid", "_is_prepared") + + xid: Any + + def __init__(self, connection: Connection, xid: Any): + self._is_prepared = False + self.xid = xid + super().__init__(connection) + + def prepare(self) -> None: + """Prepare this :class:`.TwoPhaseTransaction`. + + After a PREPARE, the transaction can be committed. + + """ + if not self.is_active: + raise exc.InvalidRequestError("This transaction is inactive") + self.connection._prepare_twophase_impl(self.xid) + self._is_prepared = True + + def _connection_begin_impl(self) -> None: + self.connection._begin_twophase_impl(self) + + def _connection_rollback_impl(self) -> None: + self.connection._rollback_twophase_impl(self.xid, self._is_prepared) + + def _connection_commit_impl(self) -> None: + self.connection._commit_twophase_impl(self.xid, self._is_prepared) + + +class Engine( + ConnectionEventsTarget, log.Identified, inspection.Inspectable["Inspector"] +): + """ + Connects a :class:`~sqlalchemy.pool.Pool` and + :class:`~sqlalchemy.engine.interfaces.Dialect` together to provide a + source of database connectivity and behavior. + + An :class:`_engine.Engine` object is instantiated publicly using the + :func:`~sqlalchemy.create_engine` function. + + .. seealso:: + + :doc:`/core/engines` + + :ref:`connections_toplevel` + + """ + + dispatch: dispatcher[ConnectionEventsTarget] + + _compiled_cache: Optional[CompiledCacheType] + + _execution_options: _ExecuteOptions = _EMPTY_EXECUTION_OPTS + _has_events: bool = False + _connection_cls: Type[Connection] = Connection + _sqla_logger_namespace: str = "sqlalchemy.engine.Engine" + _is_future: bool = False + + _schema_translate_map: Optional[SchemaTranslateMapType] = None + _option_cls: Type[OptionEngine] + + dialect: Dialect + pool: Pool + url: URL + hide_parameters: bool + + def __init__( + self, + pool: Pool, + dialect: Dialect, + url: URL, + logging_name: Optional[str] = None, + echo: Optional[_EchoFlagType] = None, + query_cache_size: int = 500, + execution_options: Optional[Mapping[str, Any]] = None, + hide_parameters: bool = False, + ): + self.pool = pool + self.url = url + self.dialect = dialect + if logging_name: + self.logging_name = logging_name + self.echo = echo + self.hide_parameters = hide_parameters + if query_cache_size != 0: + self._compiled_cache = util.LRUCache( + query_cache_size, size_alert=self._lru_size_alert + ) + else: + self._compiled_cache = None + log.instance_logger(self, echoflag=echo) + if execution_options: + self.update_execution_options(**execution_options) + + def _lru_size_alert(self, cache: util.LRUCache[Any, Any]) -> None: + if self._should_log_info(): + self.logger.info( + "Compiled cache size pruning from %d items to %d. " + "Increase cache size to reduce the frequency of pruning.", + len(cache), + cache.capacity, + ) + + @property + def engine(self) -> Engine: + """Returns this :class:`.Engine`. + + Used for legacy schemes that accept :class:`.Connection` / + :class:`.Engine` objects within the same variable. + + """ + return self + + def clear_compiled_cache(self) -> None: + """Clear the compiled cache associated with the dialect. + + This applies **only** to the built-in cache that is established + via the :paramref:`_engine.create_engine.query_cache_size` parameter. + It will not impact any dictionary caches that were passed via the + :paramref:`.Connection.execution_options.compiled_cache` parameter. + + .. versionadded:: 1.4 + + """ + if self._compiled_cache: + self._compiled_cache.clear() + + def update_execution_options(self, **opt: Any) -> None: + r"""Update the default execution_options dictionary + of this :class:`_engine.Engine`. + + The given keys/values in \**opt are added to the + default execution options that will be used for + all connections. The initial contents of this dictionary + can be sent via the ``execution_options`` parameter + to :func:`_sa.create_engine`. + + .. seealso:: + + :meth:`_engine.Connection.execution_options` + + :meth:`_engine.Engine.execution_options` + + """ + self.dispatch.set_engine_execution_options(self, opt) + self._execution_options = self._execution_options.union(opt) + self.dialect.set_engine_execution_options(self, opt) + + @overload + def execution_options( + self, + *, + compiled_cache: Optional[CompiledCacheType] = ..., + logging_token: str = ..., + isolation_level: IsolationLevel = ..., + insertmanyvalues_page_size: int = ..., + schema_translate_map: Optional[SchemaTranslateMapType] = ..., + **opt: Any, + ) -> OptionEngine: ... + + @overload + def execution_options(self, **opt: Any) -> OptionEngine: ... + + def execution_options(self, **opt: Any) -> OptionEngine: + """Return a new :class:`_engine.Engine` that will provide + :class:`_engine.Connection` objects with the given execution options. + + The returned :class:`_engine.Engine` remains related to the original + :class:`_engine.Engine` in that it shares the same connection pool and + other state: + + * The :class:`_pool.Pool` used by the new :class:`_engine.Engine` + is the + same instance. The :meth:`_engine.Engine.dispose` + method will replace + the connection pool instance for the parent engine as well + as this one. + * Event listeners are "cascaded" - meaning, the new + :class:`_engine.Engine` + inherits the events of the parent, and new events can be associated + with the new :class:`_engine.Engine` individually. + * The logging configuration and logging_name is copied from the parent + :class:`_engine.Engine`. + + The intent of the :meth:`_engine.Engine.execution_options` method is + to implement schemes where multiple :class:`_engine.Engine` + objects refer to the same connection pool, but are differentiated + by options that affect some execution-level behavior for each + engine. One such example is breaking into separate "reader" and + "writer" :class:`_engine.Engine` instances, where one + :class:`_engine.Engine` + has a lower :term:`isolation level` setting configured or is even + transaction-disabled using "autocommit". An example of this + configuration is at :ref:`dbapi_autocommit_multiple`. + + Another example is one that + uses a custom option ``shard_id`` which is consumed by an event + to change the current schema on a database connection:: + + from sqlalchemy import event + from sqlalchemy.engine import Engine + + primary_engine = create_engine("mysql+mysqldb://") + shard1 = primary_engine.execution_options(shard_id="shard1") + shard2 = primary_engine.execution_options(shard_id="shard2") + + shards = {"default": "base", "shard_1": "db1", "shard_2": "db2"} + + + @event.listens_for(Engine, "before_cursor_execute") + def _switch_shard(conn, cursor, stmt, params, context, executemany): + shard_id = conn.get_execution_options().get("shard_id", "default") + current_shard = conn.info.get("current_shard", None) + + if current_shard != shard_id: + cursor.execute("use %s" % shards[shard_id]) + conn.info["current_shard"] = shard_id + + The above recipe illustrates two :class:`_engine.Engine` objects that + will each serve as factories for :class:`_engine.Connection` objects + that have pre-established "shard_id" execution options present. A + :meth:`_events.ConnectionEvents.before_cursor_execute` event handler + then interprets this execution option to emit a MySQL ``use`` statement + to switch databases before a statement execution, while at the same + time keeping track of which database we've established using the + :attr:`_engine.Connection.info` dictionary. + + .. seealso:: + + :meth:`_engine.Connection.execution_options` + - update execution options + on a :class:`_engine.Connection` object. + + :meth:`_engine.Engine.update_execution_options` + - update the execution + options for a given :class:`_engine.Engine` in place. + + :meth:`_engine.Engine.get_execution_options` + + + """ # noqa: E501 + return self._option_cls(self, opt) + + def get_execution_options(self) -> _ExecuteOptions: + """Get the non-SQL options which will take effect during execution. + + .. versionadded: 1.3 + + .. seealso:: + + :meth:`_engine.Engine.execution_options` + """ + return self._execution_options + + @property + def name(self) -> str: + """String name of the :class:`~sqlalchemy.engine.interfaces.Dialect` + in use by this :class:`Engine`. + + """ + + return self.dialect.name + + @property + def driver(self) -> str: + """Driver name of the :class:`~sqlalchemy.engine.interfaces.Dialect` + in use by this :class:`Engine`. + + """ + + return self.dialect.driver + + echo = log.echo_property() + + def __repr__(self) -> str: + return "Engine(%r)" % (self.url,) + + def dispose(self, close: bool = True) -> None: + """Dispose of the connection pool used by this + :class:`_engine.Engine`. + + A new connection pool is created immediately after the old one has been + disposed. The previous connection pool is disposed either actively, by + closing out all currently checked-in connections in that pool, or + passively, by losing references to it but otherwise not closing any + connections. The latter strategy is more appropriate for an initializer + in a forked Python process. + + Event listeners associated with the old pool via :class:`.PoolEvents` + are **transferred to the new pool**; this is to support the pattern + by which :class:`.PoolEvents` are set up in terms of the owning + :class:`.Engine` without the need to refer to the :class:`.Pool` + directly. + + :param close: if left at its default of ``True``, has the + effect of fully closing all **currently checked in** + database connections. Connections that are still checked out + will **not** be closed, however they will no longer be associated + with this :class:`_engine.Engine`, + so when they are closed individually, eventually the + :class:`_pool.Pool` which they are associated with will + be garbage collected and they will be closed out fully, if + not already closed on checkin. + + If set to ``False``, the previous connection pool is de-referenced, + and otherwise not touched in any way. + + .. versionadded:: 1.4.33 Added the :paramref:`.Engine.dispose.close` + parameter to allow the replacement of a connection pool in a child + process without interfering with the connections used by the parent + process. + + + .. seealso:: + + :ref:`engine_disposal` + + :ref:`pooling_multiprocessing` + + :meth:`.ConnectionEvents.engine_disposed` + + """ + if close: + self.pool.dispose() + self.pool = self.pool.recreate() + self.dispatch.engine_disposed(self) + + @contextlib.contextmanager + def _optional_conn_ctx_manager( + self, connection: Optional[Connection] = None + ) -> Iterator[Connection]: + if connection is None: + with self.connect() as conn: + yield conn + else: + yield connection + + @contextlib.contextmanager + def begin(self) -> Iterator[Connection]: + """Return a context manager delivering a :class:`_engine.Connection` + with a :class:`.Transaction` established. + + E.g.:: + + with engine.begin() as conn: + conn.execute(text("insert into table (x, y, z) values (1, 2, 3)")) + conn.execute(text("my_special_procedure(5)")) + + Upon successful operation, the :class:`.Transaction` + is committed. If an error is raised, the :class:`.Transaction` + is rolled back. + + .. seealso:: + + :meth:`_engine.Engine.connect` - procure a + :class:`_engine.Connection` from + an :class:`_engine.Engine`. + + :meth:`_engine.Connection.begin` - start a :class:`.Transaction` + for a particular :class:`_engine.Connection`. + + """ # noqa: E501 + with self.connect() as conn: + with conn.begin(): + yield conn + + def _run_ddl_visitor( + self, + visitorcallable: Type[InvokeDDLBase], + element: SchemaVisitable, + **kwargs: Any, + ) -> None: + with self.begin() as conn: + conn._run_ddl_visitor(visitorcallable, element, **kwargs) + + def connect(self) -> Connection: + """Return a new :class:`_engine.Connection` object. + + The :class:`_engine.Connection` acts as a Python context manager, so + the typical use of this method looks like:: + + with engine.connect() as connection: + connection.execute(text("insert into table values ('foo')")) + connection.commit() + + Where above, after the block is completed, the connection is "closed" + and its underlying DBAPI resources are returned to the connection pool. + This also has the effect of rolling back any transaction that + was explicitly begun or was begun via autobegin, and will + emit the :meth:`_events.ConnectionEvents.rollback` event if one was + started and is still in progress. + + .. seealso:: + + :meth:`_engine.Engine.begin` + + """ + + return self._connection_cls(self) + + def raw_connection(self) -> PoolProxiedConnection: + """Return a "raw" DBAPI connection from the connection pool. + + The returned object is a proxied version of the DBAPI + connection object used by the underlying driver in use. + The object will have all the same behavior as the real DBAPI + connection, except that its ``close()`` method will result in the + connection being returned to the pool, rather than being closed + for real. + + This method provides direct DBAPI connection access for + special situations when the API provided by + :class:`_engine.Connection` + is not needed. When a :class:`_engine.Connection` object is already + present, the DBAPI connection is available using + the :attr:`_engine.Connection.connection` accessor. + + .. seealso:: + + :ref:`dbapi_connections` + + """ + return self.pool.connect() + + +class OptionEngineMixin(log.Identified): + _sa_propagate_class_events = False + + dispatch: dispatcher[ConnectionEventsTarget] + _compiled_cache: Optional[CompiledCacheType] + dialect: Dialect + pool: Pool + url: URL + hide_parameters: bool + echo: log.echo_property + + def __init__( + self, proxied: Engine, execution_options: CoreExecuteOptionsParameter + ): + self._proxied = proxied + self.url = proxied.url + self.dialect = proxied.dialect + self.logging_name = proxied.logging_name + self.echo = proxied.echo + self._compiled_cache = proxied._compiled_cache + self.hide_parameters = proxied.hide_parameters + log.instance_logger(self, echoflag=self.echo) + + # note: this will propagate events that are assigned to the parent + # engine after this OptionEngine is created. Since we share + # the events of the parent we also disallow class-level events + # to apply to the OptionEngine class directly. + # + # the other way this can work would be to transfer existing + # events only, using: + # self.dispatch._update(proxied.dispatch) + # + # that might be more appropriate however it would be a behavioral + # change for logic that assigns events to the parent engine and + # would like it to take effect for the already-created sub-engine. + self.dispatch = self.dispatch._join(proxied.dispatch) + + self._execution_options = proxied._execution_options + self.update_execution_options(**execution_options) + + def update_execution_options(self, **opt: Any) -> None: + raise NotImplementedError() + + if not typing.TYPE_CHECKING: + # https://github.com/python/typing/discussions/1095 + + @property + def pool(self) -> Pool: + return self._proxied.pool + + @pool.setter + def pool(self, pool: Pool) -> None: + self._proxied.pool = pool + + @property + def _has_events(self) -> bool: + return self._proxied._has_events or self.__dict__.get( + "_has_events", False + ) + + @_has_events.setter + def _has_events(self, value: bool) -> None: + self.__dict__["_has_events"] = value + + +class OptionEngine(OptionEngineMixin, Engine): + def update_execution_options(self, **opt: Any) -> None: + Engine.update_execution_options(self, **opt) + + +Engine._option_cls = OptionEngine diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/characteristics.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/characteristics.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d3fc56fe8e7b9fa146df7a043ab550f14ffae1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/characteristics.py @@ -0,0 +1,155 @@ +# engine/characteristics.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +from __future__ import annotations + +import abc +import typing +from typing import Any +from typing import ClassVar + +if typing.TYPE_CHECKING: + from .base import Connection + from .interfaces import DBAPIConnection + from .interfaces import Dialect + + +class ConnectionCharacteristic(abc.ABC): + """An abstract base for an object that can set, get and reset a + per-connection characteristic, typically one that gets reset when the + connection is returned to the connection pool. + + transaction isolation is the canonical example, and the + ``IsolationLevelCharacteristic`` implementation provides this for the + ``DefaultDialect``. + + The ``ConnectionCharacteristic`` class should call upon the ``Dialect`` for + the implementation of each method. The object exists strictly to serve as + a dialect visitor that can be placed into the + ``DefaultDialect.connection_characteristics`` dictionary where it will take + effect for calls to :meth:`_engine.Connection.execution_options` and + related APIs. + + .. versionadded:: 1.4 + + """ + + __slots__ = () + + transactional: ClassVar[bool] = False + + @abc.abstractmethod + def reset_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> None: + """Reset the characteristic on the DBAPI connection to its default + value.""" + + @abc.abstractmethod + def set_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any + ) -> None: + """set characteristic on the DBAPI connection to a given value.""" + + def set_connection_characteristic( + self, + dialect: Dialect, + conn: Connection, + dbapi_conn: DBAPIConnection, + value: Any, + ) -> None: + """set characteristic on the :class:`_engine.Connection` to a given + value. + + .. versionadded:: 2.0.30 - added to support elements that are local + to the :class:`_engine.Connection` itself. + + """ + self.set_characteristic(dialect, dbapi_conn, value) + + @abc.abstractmethod + def get_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> Any: + """Given a DBAPI connection, get the current value of the + characteristic. + + """ + + def get_connection_characteristic( + self, dialect: Dialect, conn: Connection, dbapi_conn: DBAPIConnection + ) -> Any: + """Given a :class:`_engine.Connection`, get the current value of the + characteristic. + + .. versionadded:: 2.0.30 - added to support elements that are local + to the :class:`_engine.Connection` itself. + + """ + return self.get_characteristic(dialect, dbapi_conn) + + +class IsolationLevelCharacteristic(ConnectionCharacteristic): + """Manage the isolation level on a DBAPI connection""" + + transactional: ClassVar[bool] = True + + def reset_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> None: + dialect.reset_isolation_level(dbapi_conn) + + def set_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any + ) -> None: + dialect._assert_and_set_isolation_level(dbapi_conn, value) + + def get_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> Any: + return dialect.get_isolation_level(dbapi_conn) + + +class LoggingTokenCharacteristic(ConnectionCharacteristic): + """Manage the 'logging_token' option of a :class:`_engine.Connection`. + + .. versionadded:: 2.0.30 + + """ + + transactional: ClassVar[bool] = False + + def reset_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> None: + pass + + def set_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any + ) -> None: + raise NotImplementedError() + + def set_connection_characteristic( + self, + dialect: Dialect, + conn: Connection, + dbapi_conn: DBAPIConnection, + value: Any, + ) -> None: + if value: + conn._message_formatter = lambda msg: "[%s] %s" % (value, msg) + else: + del conn._message_formatter + + def get_characteristic( + self, dialect: Dialect, dbapi_conn: DBAPIConnection + ) -> Any: + raise NotImplementedError() + + def get_connection_characteristic( + self, dialect: Dialect, conn: Connection, dbapi_conn: DBAPIConnection + ) -> Any: + return conn._execution_options.get("logging_token", None) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/create.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/create.py new file mode 100644 index 0000000000000000000000000000000000000000..29576e3bbb4785cd0a2e4133bcebeb59c9f08f0d --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/create.py @@ -0,0 +1,899 @@ +# engine/create.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +import inspect +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import List +from typing import Optional +from typing import overload +from typing import Type +from typing import Union + +from . import base +from . import url as _url +from .interfaces import DBAPIConnection +from .mock import create_mock_engine +from .. import event +from .. import exc +from .. import util +from ..pool import _AdhocProxiedConnection +from ..pool import ConnectionPoolEntry +from ..sql import compiler +from ..util import immutabledict + +if typing.TYPE_CHECKING: + from .base import Engine + from .interfaces import _ExecuteOptions + from .interfaces import _ParamStyle + from .interfaces import IsolationLevel + from .url import URL + from ..log import _EchoFlagType + from ..pool import _CreatorFnType + from ..pool import _CreatorWRecFnType + from ..pool import _ResetStyleArgType + from ..pool import Pool + from ..util.typing import Literal + + +@overload +def create_engine( + url: Union[str, URL], + *, + connect_args: Dict[Any, Any] = ..., + convert_unicode: bool = ..., + creator: Union[_CreatorFnType, _CreatorWRecFnType] = ..., + echo: _EchoFlagType = ..., + echo_pool: _EchoFlagType = ..., + enable_from_linting: bool = ..., + execution_options: _ExecuteOptions = ..., + future: Literal[True], + hide_parameters: bool = ..., + implicit_returning: Literal[True] = ..., + insertmanyvalues_page_size: int = ..., + isolation_level: IsolationLevel = ..., + json_deserializer: Callable[..., Any] = ..., + json_serializer: Callable[..., Any] = ..., + label_length: Optional[int] = ..., + logging_name: str = ..., + max_identifier_length: Optional[int] = ..., + max_overflow: int = ..., + module: Optional[Any] = ..., + paramstyle: Optional[_ParamStyle] = ..., + pool: Optional[Pool] = ..., + poolclass: Optional[Type[Pool]] = ..., + pool_logging_name: str = ..., + pool_pre_ping: bool = ..., + pool_size: int = ..., + pool_recycle: int = ..., + pool_reset_on_return: Optional[_ResetStyleArgType] = ..., + pool_timeout: float = ..., + pool_use_lifo: bool = ..., + plugins: List[str] = ..., + query_cache_size: int = ..., + use_insertmanyvalues: bool = ..., + **kwargs: Any, +) -> Engine: ... + + +@overload +def create_engine(url: Union[str, URL], **kwargs: Any) -> Engine: ... + + +@util.deprecated_params( + strategy=( + "1.4", + "The :paramref:`_sa.create_engine.strategy` keyword is deprecated, " + "and the only argument accepted is 'mock'; please use " + ":func:`.create_mock_engine` going forward. For general " + "customization of create_engine which may have been accomplished " + "using strategies, see :class:`.CreateEnginePlugin`.", + ), + empty_in_strategy=( + "1.4", + "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is " + "deprecated, and no longer has any effect. All IN expressions " + "are now rendered using " + 'the "expanding parameter" strategy which renders a set of bound' + 'expressions, or an "empty set" SELECT, at statement execution' + "time.", + ), + implicit_returning=( + "2.0", + "The :paramref:`_sa.create_engine.implicit_returning` parameter " + "is deprecated and will be removed in a future release. ", + ), +) +def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine: + """Create a new :class:`_engine.Engine` instance. + + The standard calling form is to send the :ref:`URL ` as the + first positional argument, usually a string + that indicates database dialect and connection arguments:: + + engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") + + .. note:: + + Please review :ref:`database_urls` for general guidelines in composing + URL strings. In particular, special characters, such as those often + part of passwords, must be URL encoded to be properly parsed. + + Additional keyword arguments may then follow it which + establish various options on the resulting :class:`_engine.Engine` + and its underlying :class:`.Dialect` and :class:`_pool.Pool` + constructs:: + + engine = create_engine( + "mysql+mysqldb://scott:tiger@hostname/dbname", + pool_recycle=3600, + echo=True, + ) + + The string form of the URL is + ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where + ``dialect`` is a database name such as ``mysql``, ``oracle``, + ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as + ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively, + the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`. + + ``**kwargs`` takes a wide variety of options which are routed + towards their appropriate components. Arguments may be specific to + the :class:`_engine.Engine`, the underlying :class:`.Dialect`, + as well as the + :class:`_pool.Pool`. Specific dialects also accept keyword arguments that + are unique to that dialect. Here, we describe the parameters + that are common to most :func:`_sa.create_engine()` usage. + + Once established, the newly resulting :class:`_engine.Engine` will + request a connection from the underlying :class:`_pool.Pool` once + :meth:`_engine.Engine.connect` is called, or a method which depends on it + such as :meth:`_engine.Engine.execute` is invoked. The + :class:`_pool.Pool` in turn + will establish the first actual DBAPI connection when this request + is received. The :func:`_sa.create_engine` call itself does **not** + establish any actual DBAPI connections directly. + + .. seealso:: + + :doc:`/core/engines` + + :doc:`/dialects/index` + + :ref:`connections_toplevel` + + :param connect_args: a dictionary of options which will be + passed directly to the DBAPI's ``connect()`` method as + additional keyword arguments. See the example + at :ref:`custom_dbapi_args`. + + :param creator: a callable which returns a DBAPI connection. + This creation function will be passed to the underlying + connection pool and will be used to create all new database + connections. Usage of this function causes connection + parameters specified in the URL argument to be bypassed. + + This hook is not as flexible as the newer + :meth:`_events.DialectEvents.do_connect` hook which allows complete + control over how a connection is made to the database, given the full + set of URL arguments and state beforehand. + + .. seealso:: + + :meth:`_events.DialectEvents.do_connect` - event hook that allows + full control over DBAPI connection mechanics. + + :ref:`custom_dbapi_args` + + :param echo=False: if True, the Engine will log all statements + as well as a ``repr()`` of their parameter lists to the default log + handler, which defaults to ``sys.stdout`` for output. If set to the + string ``"debug"``, result rows will be printed to the standard output + as well. The ``echo`` attribute of ``Engine`` can be modified at any + time to turn logging on and off; direct control of logging is also + available using the standard Python ``logging`` module. + + .. seealso:: + + :ref:`dbengine_logging` - further detail on how to configure + logging. + + + :param echo_pool=False: if True, the connection pool will log + informational output such as when connections are invalidated + as well as when connections are recycled to the default log handler, + which defaults to ``sys.stdout`` for output. If set to the string + ``"debug"``, the logging will include pool checkouts and checkins. + Direct control of logging is also available using the standard Python + ``logging`` module. + + .. seealso:: + + :ref:`dbengine_logging` - further detail on how to configure + logging. + + + :param empty_in_strategy: No longer used; SQLAlchemy now uses + "empty set" behavior for IN in all cases. + + :param enable_from_linting: defaults to True. Will emit a warning + if a given SELECT statement is found to have un-linked FROM elements + which would cause a cartesian product. + + .. versionadded:: 1.4 + + .. seealso:: + + :ref:`change_4737` + + :param execution_options: Dictionary execution options which will + be applied to all connections. See + :meth:`~sqlalchemy.engine.Connection.execution_options` + + :param future: Use the 2.0 style :class:`_engine.Engine` and + :class:`_engine.Connection` API. + + As of SQLAlchemy 2.0, this parameter is present for backwards + compatibility only and must remain at its default value of ``True``. + + The :paramref:`_sa.create_engine.future` parameter will be + deprecated in a subsequent 2.x release and eventually removed. + + .. versionadded:: 1.4 + + .. versionchanged:: 2.0 All :class:`_engine.Engine` objects are + "future" style engines and there is no longer a ``future=False`` + mode of operation. + + .. seealso:: + + :ref:`migration_20_toplevel` + + :param hide_parameters: Boolean, when set to True, SQL statement parameters + will not be displayed in INFO logging nor will they be formatted into + the string representation of :class:`.StatementError` objects. + + .. versionadded:: 1.3.8 + + .. seealso:: + + :ref:`dbengine_logging` - further detail on how to configure + logging. + + :param implicit_returning=True: Legacy parameter that may only be set + to True. In SQLAlchemy 2.0, this parameter does nothing. In order to + disable "implicit returning" for statements invoked by the ORM, + configure this on a per-table basis using the + :paramref:`.Table.implicit_returning` parameter. + + + :param insertmanyvalues_page_size: number of rows to format into an + INSERT statement when the statement uses "insertmanyvalues" mode, which is + a paged form of bulk insert that is used for many backends when using + :term:`executemany` execution typically in conjunction with RETURNING. + Defaults to 1000, but may also be subject to dialect-specific limiting + factors which may override this value on a per-statement basis. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + :ref:`engine_insertmanyvalues_page_size` + + :paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size` + + :param isolation_level: optional string name of an isolation level + which will be set on all new connections unconditionally. + Isolation levels are typically some subset of the string names + ``"SERIALIZABLE"``, ``"REPEATABLE READ"``, + ``"READ COMMITTED"``, ``"READ UNCOMMITTED"`` and ``"AUTOCOMMIT"`` + based on backend. + + The :paramref:`_sa.create_engine.isolation_level` parameter is + in contrast to the + :paramref:`.Connection.execution_options.isolation_level` + execution option, which may be set on an individual + :class:`.Connection`, as well as the same parameter passed to + :meth:`.Engine.execution_options`, where it may be used to create + multiple engines with different isolation levels that share a common + connection pool and dialect. + + .. versionchanged:: 2.0 The + :paramref:`_sa.create_engine.isolation_level` + parameter has been generalized to work on all dialects which support + the concept of isolation level, and is provided as a more succinct, + up front configuration switch in contrast to the execution option + which is more of an ad-hoc programmatic option. + + .. seealso:: + + :ref:`dbapi_autocommit` + + :param json_deserializer: for dialects that support the + :class:`_types.JSON` + datatype, this is a Python callable that will convert a JSON string + to a Python object. By default, the Python ``json.loads`` function is + used. + + .. versionchanged:: 1.3.7 The SQLite dialect renamed this from + ``_json_deserializer``. + + :param json_serializer: for dialects that support the :class:`_types.JSON` + datatype, this is a Python callable that will render a given object + as JSON. By default, the Python ``json.dumps`` function is used. + + .. versionchanged:: 1.3.7 The SQLite dialect renamed this from + ``_json_serializer``. + + + :param label_length=None: optional integer value which limits + the size of dynamically generated column labels to that many + characters. If less than 6, labels are generated as + "_(counter)". If ``None``, the value of + ``dialect.max_identifier_length``, which may be affected via the + :paramref:`_sa.create_engine.max_identifier_length` parameter, + is used instead. The value of + :paramref:`_sa.create_engine.label_length` + may not be larger than that of + :paramref:`_sa.create_engine.max_identfier_length`. + + .. seealso:: + + :paramref:`_sa.create_engine.max_identifier_length` + + :param logging_name: String identifier which will be used within + the "name" field of logging records generated within the + "sqlalchemy.engine" logger. Defaults to a hexstring of the + object's id. + + .. seealso:: + + :ref:`dbengine_logging` - further detail on how to configure + logging. + + :paramref:`_engine.Connection.execution_options.logging_token` + + :param max_identifier_length: integer; override the max_identifier_length + determined by the dialect. if ``None`` or zero, has no effect. This + is the database's configured maximum number of characters that may be + used in a SQL identifier such as a table name, column name, or label + name. All dialects determine this value automatically, however in the + case of a new database version for which this value has changed but + SQLAlchemy's dialect has not been adjusted, the value may be passed + here. + + .. versionadded:: 1.3.9 + + .. seealso:: + + :paramref:`_sa.create_engine.label_length` + + :param max_overflow=10: the number of connections to allow in + connection pool "overflow", that is connections that can be + opened above and beyond the pool_size setting, which defaults + to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`. + + :param module=None: reference to a Python module object (the module + itself, not its string name). Specifies an alternate DBAPI module to + be used by the engine's dialect. Each sub-dialect references a + specific DBAPI which will be imported before first connect. This + parameter causes the import to be bypassed, and the given module to + be used instead. Can be used for testing of DBAPIs as well as to + inject "mock" DBAPI implementations into the :class:`_engine.Engine`. + + :param paramstyle=None: The `paramstyle `_ + to use when rendering bound parameters. This style defaults to the + one recommended by the DBAPI itself, which is retrieved from the + ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept + more than one paramstyle, and in particular it may be desirable + to change a "named" paramstyle into a "positional" one, or vice versa. + When this attribute is passed, it should be one of the values + ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or + ``"pyformat"``, and should correspond to a parameter style known + to be supported by the DBAPI in use. + + :param pool=None: an already-constructed instance of + :class:`~sqlalchemy.pool.Pool`, such as a + :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this + pool will be used directly as the underlying connection pool + for the engine, bypassing whatever connection parameters are + present in the URL argument. For information on constructing + connection pools manually, see :ref:`pooling_toplevel`. + + :param poolclass=None: a :class:`~sqlalchemy.pool.Pool` + subclass, which will be used to create a connection pool + instance using the connection parameters given in the URL. Note + this differs from ``pool`` in that you don't actually + instantiate the pool in this case, you just indicate what type + of pool to be used. + + :param pool_logging_name: String identifier which will be used within + the "name" field of logging records generated within the + "sqlalchemy.pool" logger. Defaults to a hexstring of the object's + id. + + .. seealso:: + + :ref:`dbengine_logging` - further detail on how to configure + logging. + + :param pool_pre_ping: boolean, if True will enable the connection pool + "pre-ping" feature that tests connections for liveness upon + each checkout. + + .. versionadded:: 1.2 + + .. seealso:: + + :ref:`pool_disconnects_pessimistic` + + :param pool_size=5: the number of connections to keep open + inside the connection pool. This used with + :class:`~sqlalchemy.pool.QueuePool` as + well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With + :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting + of 0 indicates no limit; to disable pooling, set ``poolclass`` to + :class:`~sqlalchemy.pool.NullPool` instead. + + :param pool_recycle=-1: this setting causes the pool to recycle + connections after the given number of seconds has passed. It + defaults to -1, or no timeout. For example, setting to 3600 + means connections will be recycled after one hour. Note that + MySQL in particular will disconnect automatically if no + activity is detected on a connection for eight hours (although + this is configurable with the MySQLDB connection itself and the + server configuration as well). + + .. seealso:: + + :ref:`pool_setting_recycle` + + :param pool_reset_on_return='rollback': set the + :paramref:`_pool.Pool.reset_on_return` parameter of the underlying + :class:`_pool.Pool` object, which can be set to the values + ``"rollback"``, ``"commit"``, or ``None``. + + .. seealso:: + + :ref:`pool_reset_on_return` + + :ref:`dbapi_autocommit_skip_rollback` - a more modern approach + to using connections with no transactional instructions + + :param pool_timeout=30: number of seconds to wait before giving + up on getting a connection from the pool. This is only used + with :class:`~sqlalchemy.pool.QueuePool`. This can be a float but is + subject to the limitations of Python time functions which may not be + reliable in the tens of milliseconds. + + .. note: don't use 30.0 above, it seems to break with the :param tag + + :param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving + connections from :class:`.QueuePool` instead of FIFO + (first-in-first-out). Using LIFO, a server-side timeout scheme can + reduce the number of connections used during non- peak periods of + use. When planning for server-side timeouts, ensure that a recycle or + pre-ping strategy is in use to gracefully handle stale connections. + + .. versionadded:: 1.3 + + .. seealso:: + + :ref:`pool_use_lifo` + + :ref:`pool_disconnects` + + :param plugins: string list of plugin names to load. See + :class:`.CreateEnginePlugin` for background. + + .. versionadded:: 1.2.3 + + :param query_cache_size: size of the cache used to cache the SQL string + form of queries. Set to zero to disable caching. + + The cache is pruned of its least recently used items when its size reaches + N * 1.5. Defaults to 500, meaning the cache will always store at least + 500 SQL statements when filled, and will grow up to 750 items at which + point it is pruned back down to 500 by removing the 250 least recently + used items. + + Caching is accomplished on a per-statement basis by generating a + cache key that represents the statement's structure, then generating + string SQL for the current dialect only if that key is not present + in the cache. All statements support caching, however some features + such as an INSERT with a large set of parameters will intentionally + bypass the cache. SQL logging will indicate statistics for each + statement whether or not it were pull from the cache. + + .. note:: some ORM functions related to unit-of-work persistence as well + as some attribute loading strategies will make use of individual + per-mapper caches outside of the main cache. + + + .. seealso:: + + :ref:`sql_caching` + + .. versionadded:: 1.4 + + :param skip_autocommit_rollback: When True, the dialect will + unconditionally skip all calls to the DBAPI ``connection.rollback()`` + method if the DBAPI connection is confirmed to be in "autocommit" mode. + The availability of this feature is dialect specific; if not available, + a ``NotImplementedError`` is raised by the dialect when rollback occurs. + + .. seealso:: + + :ref:`dbapi_autocommit_skip_rollback` + + .. versionadded:: 2.0.43 + + :param use_insertmanyvalues: True by default, use the "insertmanyvalues" + execution style for INSERT..RETURNING statements by default. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + """ # noqa + + if "strategy" in kwargs: + strat = kwargs.pop("strategy") + if strat == "mock": + # this case is deprecated + return create_mock_engine(url, **kwargs) # type: ignore + else: + raise exc.ArgumentError("unknown strategy: %r" % strat) + + kwargs.pop("empty_in_strategy", None) + + # create url.URL object + u = _url.make_url(url) + + u, plugins, kwargs = u._instantiate_plugins(kwargs) + + entrypoint = u._get_entrypoint() + _is_async = kwargs.pop("_is_async", False) + if _is_async: + dialect_cls = entrypoint.get_async_dialect_cls(u) + else: + dialect_cls = entrypoint.get_dialect_cls(u) + + if kwargs.pop("_coerce_config", False): + + def pop_kwarg(key: str, default: Optional[Any] = None) -> Any: + value = kwargs.pop(key, default) + if key in dialect_cls.engine_config_types: + value = dialect_cls.engine_config_types[key](value) + return value + + else: + pop_kwarg = kwargs.pop # type: ignore + + dialect_args = {} + # consume dialect arguments from kwargs + for k in util.get_cls_kwargs(dialect_cls): + if k in kwargs: + dialect_args[k] = pop_kwarg(k) + + dbapi = kwargs.pop("module", None) + if dbapi is None: + dbapi_args = {} + + if "import_dbapi" in dialect_cls.__dict__: + dbapi_meth = dialect_cls.import_dbapi + + elif hasattr(dialect_cls, "dbapi") and inspect.ismethod( + dialect_cls.dbapi + ): + util.warn_deprecated( + "The dbapi() classmethod on dialect classes has been " + "renamed to import_dbapi(). Implement an import_dbapi() " + f"classmethod directly on class {dialect_cls} to remove this " + "warning; the old .dbapi() classmethod may be maintained for " + "backwards compatibility.", + "2.0", + ) + dbapi_meth = dialect_cls.dbapi + else: + dbapi_meth = dialect_cls.import_dbapi + + for k in util.get_func_kwargs(dbapi_meth): + if k in kwargs: + dbapi_args[k] = pop_kwarg(k) + dbapi = dbapi_meth(**dbapi_args) + + dialect_args["dbapi"] = dbapi + + dialect_args.setdefault("compiler_linting", compiler.NO_LINTING) + enable_from_linting = kwargs.pop("enable_from_linting", True) + if enable_from_linting: + dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS + + for plugin in plugins: + plugin.handle_dialect_kwargs(dialect_cls, dialect_args) + + # create dialect + dialect = dialect_cls(**dialect_args) + + # assemble connection arguments + (cargs_tup, _cparams) = dialect.create_connect_args(u) + cparams = util.immutabledict(_cparams).union(pop_kwarg("connect_args", {})) + + if "async_fallback" in cparams and util.asbool(cparams["async_fallback"]): + util.warn_deprecated( + "The async_fallback dialect argument is deprecated and will be " + "removed in SQLAlchemy 2.1.", + "2.0", + ) + + # look for existing pool or create + pool = pop_kwarg("pool", None) + if pool is None: + + def connect( + connection_record: Optional[ConnectionPoolEntry] = None, + ) -> DBAPIConnection: + if dialect._has_events: + mutable_cargs = list(cargs_tup) + mutable_cparams = dict(cparams) + for fn in dialect.dispatch.do_connect: + connection = cast( + DBAPIConnection, + fn( + dialect, + connection_record, + mutable_cargs, + mutable_cparams, + ), + ) + if connection is not None: + return connection + return dialect.connect(*mutable_cargs, **mutable_cparams) + else: + return dialect.connect(*cargs_tup, **cparams) + + creator = pop_kwarg("creator", connect) + + poolclass = pop_kwarg("poolclass", None) + if poolclass is None: + poolclass = dialect.get_dialect_pool_class(u) + pool_args = {"dialect": dialect} + + # consume pool arguments from kwargs, translating a few of + # the arguments + for k in util.get_cls_kwargs(poolclass): + tk = _pool_translate_kwargs.get(k, k) + if tk in kwargs: + pool_args[k] = pop_kwarg(tk) + + for plugin in plugins: + plugin.handle_pool_kwargs(poolclass, pool_args) + + pool = poolclass(creator, **pool_args) + else: + pool._dialect = dialect + + if ( + hasattr(pool, "_is_asyncio") + and pool._is_asyncio is not dialect.is_async + ): + raise exc.ArgumentError( + f"Pool class {pool.__class__.__name__} cannot be " + f"used with {'non-' if not dialect.is_async else ''}" + "asyncio engine", + code="pcls", + ) + + # create engine. + if not pop_kwarg("future", True): + raise exc.ArgumentError( + "The 'future' parameter passed to " + "create_engine() may only be set to True." + ) + + engineclass = base.Engine + + engine_args = {} + for k in util.get_cls_kwargs(engineclass): + if k in kwargs: + engine_args[k] = pop_kwarg(k) + + # internal flags used by the test suite for instrumenting / proxying + # engines with mocks etc. + _initialize = kwargs.pop("_initialize", True) + + # all kwargs should be consumed + if kwargs: + raise TypeError( + "Invalid argument(s) %s sent to create_engine(), " + "using configuration %s/%s/%s. Please check that the " + "keyword arguments are appropriate for this combination " + "of components." + % ( + ",".join("'%s'" % k for k in kwargs), + dialect.__class__.__name__, + pool.__class__.__name__, + engineclass.__name__, + ) + ) + + engine = engineclass(pool, dialect, u, **engine_args) + + if _initialize: + do_on_connect = dialect.on_connect_url(u) + if do_on_connect: + + def on_connect( + dbapi_connection: DBAPIConnection, + connection_record: ConnectionPoolEntry, + ) -> None: + assert do_on_connect is not None + do_on_connect(dbapi_connection) + + event.listen(pool, "connect", on_connect) + + builtin_on_connect = dialect._builtin_onconnect() + if builtin_on_connect: + event.listen(pool, "connect", builtin_on_connect) + + def first_connect( + dbapi_connection: DBAPIConnection, + connection_record: ConnectionPoolEntry, + ) -> None: + c = base.Connection( + engine, + connection=_AdhocProxiedConnection( + dbapi_connection, connection_record + ), + _has_events=False, + # reconnecting will be a reentrant condition, so if the + # connection goes away, Connection is then closed + _allow_revalidate=False, + # dont trigger the autobegin sequence + # within the up front dialect checks + _allow_autobegin=False, + ) + c._execution_options = util.EMPTY_DICT + + try: + dialect.initialize(c) + finally: + # note that "invalidated" and "closed" are mutually + # exclusive in 1.4 Connection. + if not c.invalidated and not c.closed: + # transaction is rolled back otherwise, tested by + # test/dialect/postgresql/test_dialect.py + # ::MiscBackendTest::test_initial_transaction_state + dialect.do_rollback(c.connection) + + # previously, the "first_connect" event was used here, which was then + # scaled back if the "on_connect" handler were present. now, + # since "on_connect" is virtually always present, just use + # "connect" event with once_unless_exception in all cases so that + # the connection event flow is consistent in all cases. + event.listen( + pool, "connect", first_connect, _once_unless_exception=True + ) + + dialect_cls.engine_created(engine) + if entrypoint is not dialect_cls: + entrypoint.engine_created(engine) + + for plugin in plugins: + plugin.engine_created(engine) + + return engine + + +def engine_from_config( + configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any +) -> Engine: + """Create a new Engine instance using a configuration dictionary. + + The dictionary is typically produced from a config file. + + The keys of interest to ``engine_from_config()`` should be prefixed, e.g. + ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument + indicates the prefix to be searched for. Each matching key (after the + prefix is stripped) is treated as though it were the corresponding keyword + argument to a :func:`_sa.create_engine` call. + + The only required key is (assuming the default prefix) ``sqlalchemy.url``, + which provides the :ref:`database URL `. + + A select set of keyword arguments will be "coerced" to their + expected type based on string values. The set of arguments + is extensible per-dialect using the ``engine_config_types`` accessor. + + :param configuration: A dictionary (typically produced from a config file, + but this is not a requirement). Items whose keys start with the value + of 'prefix' will have that prefix stripped, and will then be passed to + :func:`_sa.create_engine`. + + :param prefix: Prefix to match and then strip from keys + in 'configuration'. + + :param kwargs: Each keyword argument to ``engine_from_config()`` itself + overrides the corresponding item taken from the 'configuration' + dictionary. Keyword arguments should *not* be prefixed. + + """ + + options = { + key[len(prefix) :]: configuration[key] + for key in configuration + if key.startswith(prefix) + } + options["_coerce_config"] = True + options.update(kwargs) + url = options.pop("url") + return create_engine(url, **options) + + +@overload +def create_pool_from_url( + url: Union[str, URL], + *, + poolclass: Optional[Type[Pool]] = ..., + logging_name: str = ..., + pre_ping: bool = ..., + size: int = ..., + recycle: int = ..., + reset_on_return: Optional[_ResetStyleArgType] = ..., + timeout: float = ..., + use_lifo: bool = ..., + **kwargs: Any, +) -> Pool: ... + + +@overload +def create_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool: ... + + +def create_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool: + """Create a pool instance from the given url. + + If ``poolclass`` is not provided the pool class used + is selected using the dialect specified in the URL. + + The arguments passed to :func:`_sa.create_pool_from_url` are + identical to the pool argument passed to the :func:`_sa.create_engine` + function. + + .. versionadded:: 2.0.10 + """ + + for key in _pool_translate_kwargs: + if key in kwargs: + kwargs[_pool_translate_kwargs[key]] = kwargs.pop(key) + + engine = create_engine(url, **kwargs, _initialize=False) + return engine.pool + + +_pool_translate_kwargs = immutabledict( + { + "logging_name": "pool_logging_name", + "echo": "echo_pool", + "timeout": "pool_timeout", + "recycle": "pool_recycle", + "events": "pool_events", # deprecated + "reset_on_return": "pool_reset_on_return", + "pre_ping": "pool_pre_ping", + "use_lifo": "pool_use_lifo", + } +) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/cursor.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/cursor.py new file mode 100644 index 0000000000000000000000000000000000000000..3151463b30a670ce3c834beabf472b24a0825a26 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/cursor.py @@ -0,0 +1,2303 @@ +# engine/cursor.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Define cursor-specific result set constructs including +:class:`.CursorResult`.""" + + +from __future__ import annotations + +import collections +import functools +import operator +import typing +from typing import Any +from typing import cast +from typing import ClassVar +from typing import Deque +from typing import Dict +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .result import IteratorResult +from .result import MergedResult +from .result import Result +from .result import ResultMetaData +from .result import SimpleResultMetaData +from .result import tuplegetter +from .row import Row +from .. import exc +from .. import util +from ..sql import elements +from ..sql import sqltypes +from ..sql import util as sql_util +from ..sql.base import _generative +from ..sql.compiler import ResultColumnsEntry +from ..sql.compiler import RM_NAME +from ..sql.compiler import RM_OBJECTS +from ..sql.compiler import RM_RENDERED_NAME +from ..sql.compiler import RM_TYPE +from ..sql.type_api import TypeEngine +from ..util import compat +from ..util.typing import Final +from ..util.typing import Literal +from ..util.typing import Self + + +if typing.TYPE_CHECKING: + from .base import Connection + from .default import DefaultExecutionContext + from .interfaces import _DBAPICursorDescription + from .interfaces import _MutableCoreSingleExecuteParams + from .interfaces import CoreExecuteOptionsParameter + from .interfaces import DBAPICursor + from .interfaces import DBAPIType + from .interfaces import Dialect + from .interfaces import ExecutionContext + from .result import _KeyIndexType + from .result import _KeyMapRecType + from .result import _KeyMapType + from .result import _KeyType + from .result import _ProcessorsType + from .result import _TupleGetterType + from ..sql.schema import Column + from ..sql.type_api import _ResultProcessorType + + +_T = TypeVar("_T", bound=Any) +TupleAny = Tuple[Any, ...] + +# metadata entry tuple indexes. +# using raw tuple is faster than namedtuple. +# these match up to the positions in +# _CursorKeyMapRecType +MD_INDEX: Final[Literal[0]] = 0 +"""integer index in cursor.description + +""" + +MD_RESULT_MAP_INDEX: Final[Literal[1]] = 1 +"""integer index in compiled._result_columns""" + +MD_OBJECTS: Final[Literal[2]] = 2 +"""other string keys and ColumnElement obj that can match. + +This comes from compiler.RM_OBJECTS / compiler.ResultColumnsEntry.objects + +""" + +MD_LOOKUP_KEY: Final[Literal[3]] = 3 +"""string key we usually expect for key-based lookup + +this comes from compiler.RM_NAME / compiler.ResultColumnsEntry.name +""" + + +MD_RENDERED_NAME: Final[Literal[4]] = 4 +"""name that is usually in cursor.description + +this comes from compiler.RENDERED_NAME / compiler.ResultColumnsEntry.keyname +""" + + +MD_PROCESSOR: Final[Literal[5]] = 5 +"""callable to process a result value into a row""" + +MD_UNTRANSLATED: Final[Literal[6]] = 6 +"""raw name from cursor.description""" + + +_CursorKeyMapRecType = Tuple[ + Optional[int], # MD_INDEX, None means the record is ambiguously named + int, # MD_RESULT_MAP_INDEX, -1 if MD_INDEX is None + TupleAny, # MD_OBJECTS + str, # MD_LOOKUP_KEY + str, # MD_RENDERED_NAME + Optional["_ResultProcessorType[Any]"], # MD_PROCESSOR + Optional[str], # MD_UNTRANSLATED +] + +_CursorKeyMapType = Mapping["_KeyType", _CursorKeyMapRecType] + +# same as _CursorKeyMapRecType except the MD_INDEX value is definitely +# not None +_NonAmbigCursorKeyMapRecType = Tuple[ + int, + int, + List[Any], + str, + str, + Optional["_ResultProcessorType[Any]"], + str, +] + +_MergeColTuple = Tuple[ + int, + Optional[int], + str, + TypeEngine[Any], + "DBAPIType", + Optional[TupleAny], + Optional[str], +] + + +class CursorResultMetaData(ResultMetaData): + """Result metadata for DBAPI cursors.""" + + __slots__ = ( + "_keymap", + "_processors", + "_keys", + "_keymap_by_result_column_idx", + "_tuplefilter", + "_translated_indexes", + "_safe_for_cache", + "_unpickled", + "_key_to_index", + # don't need _unique_filters support here for now. Can be added + # if a need arises. + ) + + _keymap: _CursorKeyMapType + _processors: _ProcessorsType + _keymap_by_result_column_idx: Optional[Dict[int, _KeyMapRecType]] + _unpickled: bool + _safe_for_cache: bool + _translated_indexes: Optional[List[int]] + + returns_rows: ClassVar[bool] = True + + def _has_key(self, key: Any) -> bool: + return key in self._keymap + + def _for_freeze(self) -> ResultMetaData: + return SimpleResultMetaData( + self._keys, + extra=[self._keymap[key][MD_OBJECTS] for key in self._keys], + ) + + def _make_new_metadata( + self, + *, + unpickled: bool, + processors: _ProcessorsType, + keys: Sequence[str], + keymap: _KeyMapType, + tuplefilter: Optional[_TupleGetterType], + translated_indexes: Optional[List[int]], + safe_for_cache: bool, + keymap_by_result_column_idx: Any, + ) -> CursorResultMetaData: + new_obj = self.__class__.__new__(self.__class__) + new_obj._unpickled = unpickled + new_obj._processors = processors + new_obj._keys = keys + new_obj._keymap = keymap + new_obj._tuplefilter = tuplefilter + new_obj._translated_indexes = translated_indexes + new_obj._safe_for_cache = safe_for_cache + new_obj._keymap_by_result_column_idx = keymap_by_result_column_idx + new_obj._key_to_index = self._make_key_to_index(keymap, MD_INDEX) + return new_obj + + def _remove_processors(self) -> CursorResultMetaData: + assert not self._tuplefilter + return self._make_new_metadata( + unpickled=self._unpickled, + processors=[None] * len(self._processors), + tuplefilter=None, + translated_indexes=None, + keymap={ + key: value[0:5] + (None,) + value[6:] + for key, value in self._keymap.items() + }, + keys=self._keys, + safe_for_cache=self._safe_for_cache, + keymap_by_result_column_idx=self._keymap_by_result_column_idx, + ) + + def _splice_horizontally( + self, other: CursorResultMetaData + ) -> CursorResultMetaData: + assert not self._tuplefilter + + keymap = dict(self._keymap) + offset = len(self._keys) + + for key, value in other._keymap.items(): + # int index should be None for ambiguous key + if value[MD_INDEX] is not None and key not in keymap: + md_index = value[MD_INDEX] + offset + md_object = value[MD_RESULT_MAP_INDEX] + offset + else: + md_index = None + md_object = -1 + keymap[key] = (md_index, md_object, *value[2:]) + + return self._make_new_metadata( + unpickled=self._unpickled, + processors=self._processors + other._processors, # type: ignore + tuplefilter=None, + translated_indexes=None, + keys=self._keys + other._keys, # type: ignore + keymap=keymap, + safe_for_cache=self._safe_for_cache, + keymap_by_result_column_idx={ + metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry + for metadata_entry in keymap.values() + }, + ) + + def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData: + recs = list(self._metadata_for_keys(keys)) + + indexes = [rec[MD_INDEX] for rec in recs] + new_keys: List[str] = [rec[MD_LOOKUP_KEY] for rec in recs] + + if self._translated_indexes: + indexes = [self._translated_indexes[idx] for idx in indexes] + tup = tuplegetter(*indexes) + new_recs = [(index,) + rec[1:] for index, rec in enumerate(recs)] + + keymap = {rec[MD_LOOKUP_KEY]: rec for rec in new_recs} + # TODO: need unit test for: + # result = connection.execute("raw sql, no columns").scalars() + # without the "or ()" it's failing because MD_OBJECTS is None + keymap.update( + (e, new_rec) + for new_rec in new_recs + for e in new_rec[MD_OBJECTS] or () + ) + + return self._make_new_metadata( + unpickled=self._unpickled, + processors=self._processors, + keys=new_keys, + tuplefilter=tup, + translated_indexes=indexes, + keymap=keymap, # type: ignore[arg-type] + safe_for_cache=self._safe_for_cache, + keymap_by_result_column_idx=self._keymap_by_result_column_idx, + ) + + def _adapt_to_context(self, context: ExecutionContext) -> ResultMetaData: + """When using a cached Compiled construct that has a _result_map, + for a new statement that used the cached Compiled, we need to ensure + the keymap has the Column objects from our new statement as keys. + So here we rewrite keymap with new entries for the new columns + as matched to those of the cached statement. + + """ + + if not context.compiled or not context.compiled._result_columns: + return self + + compiled_statement = context.compiled.statement + invoked_statement = context.invoked_statement + + if TYPE_CHECKING: + assert isinstance(invoked_statement, elements.ClauseElement) + + if compiled_statement is invoked_statement: + return self + + assert invoked_statement is not None + + # this is the most common path for Core statements when + # caching is used. In ORM use, this codepath is not really used + # as the _result_disable_adapt_to_context execution option is + # set by the ORM. + + # make a copy and add the columns from the invoked statement + # to the result map. + + keymap_by_position = self._keymap_by_result_column_idx + + if keymap_by_position is None: + # first retrieval from cache, this map will not be set up yet, + # initialize lazily + keymap_by_position = self._keymap_by_result_column_idx = { + metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry + for metadata_entry in self._keymap.values() + } + + assert not self._tuplefilter + return self._make_new_metadata( + keymap=compat.dict_union( + self._keymap, + { + new: keymap_by_position[idx] + for idx, new in enumerate( + invoked_statement._all_selected_columns + ) + if idx in keymap_by_position + }, + ), + unpickled=self._unpickled, + processors=self._processors, + tuplefilter=None, + translated_indexes=None, + keys=self._keys, + safe_for_cache=self._safe_for_cache, + keymap_by_result_column_idx=self._keymap_by_result_column_idx, + ) + + def __init__( + self, + parent: CursorResult[Any], + cursor_description: _DBAPICursorDescription, + ): + context = parent.context + self._tuplefilter = None + self._translated_indexes = None + self._safe_for_cache = self._unpickled = False + + if context.result_column_struct: + ( + result_columns, + cols_are_ordered, + textual_ordered, + ad_hoc_textual, + loose_column_name_matching, + ) = context.result_column_struct + num_ctx_cols = len(result_columns) + else: + result_columns = cols_are_ordered = ( # type: ignore + num_ctx_cols + ) = ad_hoc_textual = loose_column_name_matching = ( + textual_ordered + ) = False + + # merge cursor.description with the column info + # present in the compiled structure, if any + raw = self._merge_cursor_description( + context, + cursor_description, + result_columns, + num_ctx_cols, + cols_are_ordered, + textual_ordered, + ad_hoc_textual, + loose_column_name_matching, + ) + + # processors in key order which are used when building up + # a row + self._processors = [ + metadata_entry[MD_PROCESSOR] for metadata_entry in raw + ] + + # this is used when using this ResultMetaData in a Core-only cache + # retrieval context. it's initialized on first cache retrieval + # when the _result_disable_adapt_to_context execution option + # (which the ORM generally sets) is not set. + self._keymap_by_result_column_idx = None + + # for compiled SQL constructs, copy additional lookup keys into + # the key lookup map, such as Column objects, labels, + # column keys and other names + if num_ctx_cols: + # keymap by primary string... + by_key: Dict[_KeyType, _CursorKeyMapRecType] = { + metadata_entry[MD_LOOKUP_KEY]: metadata_entry + for metadata_entry in raw + } + + if len(by_key) != num_ctx_cols: + # if by-primary-string dictionary smaller than + # number of columns, assume we have dupes; (this check + # is also in place if string dictionary is bigger, as + # can occur when '*' was used as one of the compiled columns, + # which may or may not be suggestive of dupes), rewrite + # dupe records with "None" for index which results in + # ambiguous column exception when accessed. + # + # this is considered to be the less common case as it is not + # common to have dupe column keys in a SELECT statement. + # + # new in 1.4: get the complete set of all possible keys, + # strings, objects, whatever, that are dupes across two + # different records, first. + index_by_key: Dict[Any, Any] = {} + dupes = set() + for metadata_entry in raw: + for key in (metadata_entry[MD_RENDERED_NAME],) + ( + metadata_entry[MD_OBJECTS] or () + ): + idx = metadata_entry[MD_INDEX] + # if this key has been associated with more than one + # positional index, it's a dupe + if index_by_key.setdefault(key, idx) != idx: + dupes.add(key) + + # then put everything we have into the keymap excluding only + # those keys that are dupes. + self._keymap = { + obj_elem: metadata_entry + for metadata_entry in raw + if metadata_entry[MD_OBJECTS] + for obj_elem in metadata_entry[MD_OBJECTS] + if obj_elem not in dupes + } + + # then for the dupe keys, put the "ambiguous column" + # record into by_key. + by_key.update( + { + key: (None, -1, (), key, key, None, None) + for key in dupes + } + ) + + else: + # no dupes - copy secondary elements from compiled + # columns into self._keymap. this is the most common + # codepath for Core / ORM statement executions before the + # result metadata is cached + self._keymap = { + obj_elem: metadata_entry + for metadata_entry in raw + if metadata_entry[MD_OBJECTS] + for obj_elem in metadata_entry[MD_OBJECTS] + } + # update keymap with primary string names taking + # precedence + self._keymap.update(by_key) + else: + # no compiled objects to map, just create keymap by primary string + self._keymap = { + metadata_entry[MD_LOOKUP_KEY]: metadata_entry + for metadata_entry in raw + } + + # update keymap with "translated" names. In SQLAlchemy this is a + # sqlite only thing, and in fact impacting only extremely old SQLite + # versions unlikely to be present in modern Python versions. + # however, the pyhive third party dialect is + # also using this hook, which means others still might use it as well. + # I dislike having this awkward hook here but as long as we need + # to use names in cursor.description in some cases we need to have + # some hook to accomplish this. + if not num_ctx_cols and context._translate_colname: + self._keymap.update( + { + metadata_entry[MD_UNTRANSLATED]: self._keymap[ + metadata_entry[MD_LOOKUP_KEY] + ] + for metadata_entry in raw + if metadata_entry[MD_UNTRANSLATED] + } + ) + + self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX) + + def _merge_cursor_description( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + result_columns: Sequence[ResultColumnsEntry], + num_ctx_cols: int, + cols_are_ordered: bool, + textual_ordered: bool, + ad_hoc_textual: bool, + loose_column_name_matching: bool, + ) -> List[_CursorKeyMapRecType]: + """Merge a cursor.description with compiled result column information. + + There are at least four separate strategies used here, selected + depending on the type of SQL construct used to start with. + + The most common case is that of the compiled SQL expression construct, + which generated the column names present in the raw SQL string and + which has the identical number of columns as were reported by + cursor.description. In this case, we assume a 1-1 positional mapping + between the entries in cursor.description and the compiled object. + This is also the most performant case as we disregard extracting / + decoding the column names present in cursor.description since we + already have the desired name we generated in the compiled SQL + construct. + + The next common case is that of the completely raw string SQL, + such as passed to connection.execute(). In this case we have no + compiled construct to work with, so we extract and decode the + names from cursor.description and index those as the primary + result row target keys. + + The remaining fairly common case is that of the textual SQL + that includes at least partial column information; this is when + we use a :class:`_expression.TextualSelect` construct. + This construct may have + unordered or ordered column information. In the ordered case, we + merge the cursor.description and the compiled construct's information + positionally, and warn if there are additional description names + present, however we still decode the names in cursor.description + as we don't have a guarantee that the names in the columns match + on these. In the unordered case, we match names in cursor.description + to that of the compiled construct based on name matching. + In both of these cases, the cursor.description names and the column + expression objects and names are indexed as result row target keys. + + The final case is much less common, where we have a compiled + non-textual SQL expression construct, but the number of columns + in cursor.description doesn't match what's in the compiled + construct. We make the guess here that there might be textual + column expressions in the compiled construct that themselves include + a comma in them causing them to split. We do the same name-matching + as with textual non-ordered columns. + + The name-matched system of merging is the same as that used by + SQLAlchemy for all cases up through the 0.9 series. Positional + matching for compiled SQL expressions was introduced in 1.0 as a + major performance feature, and positional matching for textual + :class:`_expression.TextualSelect` objects in 1.1. + As name matching is no longer + a common case, it was acceptable to factor it into smaller generator- + oriented methods that are easier to understand, but incur slightly + more performance overhead. + + """ + + if ( + num_ctx_cols + and cols_are_ordered + and not textual_ordered + and num_ctx_cols == len(cursor_description) + ): + self._keys = [elem[0] for elem in result_columns] + # pure positional 1-1 case; doesn't need to read + # the names from cursor.description + + # most common case for Core and ORM + + # this metadata is safe to cache because we are guaranteed + # to have the columns in the same order for new executions + self._safe_for_cache = True + return [ + ( + idx, + idx, + rmap_entry[RM_OBJECTS], + rmap_entry[RM_NAME], + rmap_entry[RM_RENDERED_NAME], + context.get_result_processor( + rmap_entry[RM_TYPE], + rmap_entry[RM_RENDERED_NAME], + cursor_description[idx][1], + ), + None, + ) + for idx, rmap_entry in enumerate(result_columns) + ] + else: + # name-based or text-positional cases, where we need + # to read cursor.description names + + if textual_ordered or ( + ad_hoc_textual and len(cursor_description) == num_ctx_cols + ): + self._safe_for_cache = True + # textual positional case + raw_iterator = self._merge_textual_cols_by_position( + context, cursor_description, result_columns + ) + elif num_ctx_cols: + # compiled SQL with a mismatch of description cols + # vs. compiled cols, or textual w/ unordered columns + # the order of columns can change if the query is + # against a "select *", so not safe to cache + self._safe_for_cache = False + raw_iterator = self._merge_cols_by_name( + context, + cursor_description, + result_columns, + loose_column_name_matching, + ) + else: + # no compiled SQL, just a raw string, order of columns + # can change for "select *" + self._safe_for_cache = False + raw_iterator = self._merge_cols_by_none( + context, cursor_description + ) + + return [ + ( + idx, + ridx, + obj, + cursor_colname, + cursor_colname, + context.get_result_processor( + mapped_type, cursor_colname, coltype + ), + untranslated, + ) # type: ignore[misc] + for ( + idx, + ridx, + cursor_colname, + mapped_type, + coltype, + obj, + untranslated, + ) in raw_iterator + ] + + def _colnames_from_description( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + ) -> Iterator[Tuple[int, str, Optional[str], DBAPIType]]: + """Extract column names and data types from a cursor.description. + + Applies unicode decoding, column translation, "normalization", + and case sensitivity rules to the names based on the dialect. + + """ + + dialect = context.dialect + translate_colname = context._translate_colname + normalize_name = ( + dialect.normalize_name if dialect.requires_name_normalize else None + ) + untranslated = None + + self._keys = [] + + for idx, rec in enumerate(cursor_description): + colname = rec[0] + coltype = rec[1] + + if translate_colname: + colname, untranslated = translate_colname(colname) + + if normalize_name: + colname = normalize_name(colname) + + self._keys.append(colname) + + yield idx, colname, untranslated, coltype + + def _merge_textual_cols_by_position( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + result_columns: Sequence[ResultColumnsEntry], + ) -> Iterator[_MergeColTuple]: + num_ctx_cols = len(result_columns) + + if num_ctx_cols > len(cursor_description): + util.warn( + "Number of columns in textual SQL (%d) is " + "smaller than number of columns requested (%d)" + % (num_ctx_cols, len(cursor_description)) + ) + seen = set() + + for ( + idx, + colname, + untranslated, + coltype, + ) in self._colnames_from_description(context, cursor_description): + if idx < num_ctx_cols: + ctx_rec = result_columns[idx] + obj = ctx_rec[RM_OBJECTS] + ridx = idx + mapped_type = ctx_rec[RM_TYPE] + if obj[0] in seen: + raise exc.InvalidRequestError( + "Duplicate column expression requested " + "in textual SQL: %r" % obj[0] + ) + seen.add(obj[0]) + else: + mapped_type = sqltypes.NULLTYPE + obj = None + ridx = None + yield idx, ridx, colname, mapped_type, coltype, obj, untranslated + + def _merge_cols_by_name( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + result_columns: Sequence[ResultColumnsEntry], + loose_column_name_matching: bool, + ) -> Iterator[_MergeColTuple]: + match_map = self._create_description_match_map( + result_columns, loose_column_name_matching + ) + mapped_type: TypeEngine[Any] + + for ( + idx, + colname, + untranslated, + coltype, + ) in self._colnames_from_description(context, cursor_description): + try: + ctx_rec = match_map[colname] + except KeyError: + mapped_type = sqltypes.NULLTYPE + obj = None + result_columns_idx = None + else: + obj = ctx_rec[1] + mapped_type = ctx_rec[2] + result_columns_idx = ctx_rec[3] + yield ( + idx, + result_columns_idx, + colname, + mapped_type, + coltype, + obj, + untranslated, + ) + + @classmethod + def _create_description_match_map( + cls, + result_columns: Sequence[ResultColumnsEntry], + loose_column_name_matching: bool = False, + ) -> Dict[Union[str, object], Tuple[str, TupleAny, TypeEngine[Any], int]]: + """when matching cursor.description to a set of names that are present + in a Compiled object, as is the case with TextualSelect, get all the + names we expect might match those in cursor.description. + """ + + d: Dict[ + Union[str, object], + Tuple[str, TupleAny, TypeEngine[Any], int], + ] = {} + for ridx, elem in enumerate(result_columns): + key = elem[RM_RENDERED_NAME] + if key in d: + # conflicting keyname - just add the column-linked objects + # to the existing record. if there is a duplicate column + # name in the cursor description, this will allow all of those + # objects to raise an ambiguous column error + e_name, e_obj, e_type, e_ridx = d[key] + d[key] = e_name, e_obj + elem[RM_OBJECTS], e_type, ridx + else: + d[key] = (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx) + + if loose_column_name_matching: + # when using a textual statement with an unordered set + # of columns that line up, we are expecting the user + # to be using label names in the SQL that match to the column + # expressions. Enable more liberal matching for this case; + # duplicate keys that are ambiguous will be fixed later. + for r_key in elem[RM_OBJECTS]: + d.setdefault( + r_key, + (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx), + ) + return d + + def _merge_cols_by_none( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + ) -> Iterator[_MergeColTuple]: + self._keys = [] + + for ( + idx, + colname, + untranslated, + coltype, + ) in self._colnames_from_description(context, cursor_description): + yield ( + idx, + None, + colname, + sqltypes.NULLTYPE, + coltype, + None, + untranslated, + ) + + if not TYPE_CHECKING: + + def _key_fallback( + self, key: Any, err: Optional[Exception], raiseerr: bool = True + ) -> Optional[NoReturn]: + if raiseerr: + if self._unpickled and isinstance(key, elements.ColumnElement): + raise exc.NoSuchColumnError( + "Row was unpickled; lookup by ColumnElement " + "is unsupported" + ) from err + else: + raise exc.NoSuchColumnError( + "Could not locate column in row for column '%s'" + % util.string_or_unprintable(key) + ) from err + else: + return None + + def _raise_for_ambiguous_column_name( + self, rec: _KeyMapRecType + ) -> NoReturn: + raise exc.InvalidRequestError( + "Ambiguous column name '%s' in " + "result set column descriptions" % rec[MD_LOOKUP_KEY] + ) + + def _index_for_key( + self, key: _KeyIndexType, raiseerr: bool = True + ) -> Optional[int]: + # TODO: can consider pre-loading ints and negative ints + # into _keymap - also no coverage here + if isinstance(key, int): + key = self._keys[key] + + try: + rec = self._keymap[key] + except KeyError as ke: + x = self._key_fallback(key, ke, raiseerr) + assert x is None + return None + + index = rec[0] + + if index is None: + self._raise_for_ambiguous_column_name(rec) + return index + + def _indexes_for_keys( + self, keys: Sequence[_KeyIndexType] + ) -> Sequence[int]: + try: + return [self._keymap[key][0] for key in keys] # type: ignore[index,misc] # noqa: E501 + except KeyError as ke: + # ensure it raises + CursorResultMetaData._key_fallback(self, ke.args[0], ke) + + def _metadata_for_keys( + self, keys: Sequence[_KeyIndexType] + ) -> Iterator[_NonAmbigCursorKeyMapRecType]: + for key in keys: + if int in key.__class__.__mro__: + key = self._keys[key] # type: ignore[index] + + try: + rec = self._keymap[key] # type: ignore[index] + except KeyError as ke: + # ensure it raises + CursorResultMetaData._key_fallback(self, ke.args[0], ke) + + index = rec[MD_INDEX] + + if index is None: + self._raise_for_ambiguous_column_name(rec) + + yield cast(_NonAmbigCursorKeyMapRecType, rec) + + def __getstate__(self) -> Dict[str, Any]: + # TODO: consider serializing this as SimpleResultMetaData + return { + "_keymap": { + key: ( + rec[MD_INDEX], + rec[MD_RESULT_MAP_INDEX], + [], + key, + rec[MD_RENDERED_NAME], + None, + None, + ) + for key, rec in self._keymap.items() + if isinstance(key, (str, int)) + }, + "_keys": self._keys, + "_translated_indexes": self._translated_indexes, + } + + def __setstate__(self, state: Dict[str, Any]) -> None: + self._processors = [None for _ in range(len(state["_keys"]))] + self._keymap = state["_keymap"] + self._keymap_by_result_column_idx = None + self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX) + self._keys = state["_keys"] + self._unpickled = True + if state["_translated_indexes"]: + self._translated_indexes = cast( + "List[int]", state["_translated_indexes"] + ) + self._tuplefilter = tuplegetter(*self._translated_indexes) + else: + self._translated_indexes = self._tuplefilter = None + + +class ResultFetchStrategy: + """Define a fetching strategy for a result object. + + + .. versionadded:: 1.4 + + """ + + __slots__ = () + + alternate_cursor_description: Optional[_DBAPICursorDescription] = None + + def soft_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + raise NotImplementedError() + + def hard_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + raise NotImplementedError() + + def yield_per( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + num: int, + ) -> None: + return + + def fetchone( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + hard_close: bool = False, + ) -> Any: + raise NotImplementedError() + + def fetchmany( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + size: Optional[int] = None, + ) -> Any: + raise NotImplementedError() + + def fetchall( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + ) -> Any: + raise NotImplementedError() + + def handle_exception( + self, + result: CursorResult[Any], + dbapi_cursor: Optional[DBAPICursor], + err: BaseException, + ) -> NoReturn: + raise err + + +class NoCursorFetchStrategy(ResultFetchStrategy): + """Cursor strategy for a result that has no open cursor. + + There are two varieties of this strategy, one for DQL and one for + DML (and also DDL), each of which represent a result that had a cursor + but no longer has one. + + """ + + __slots__ = () + + def soft_close( + self, + result: CursorResult[Any], + dbapi_cursor: Optional[DBAPICursor], + ) -> None: + pass + + def hard_close( + self, + result: CursorResult[Any], + dbapi_cursor: Optional[DBAPICursor], + ) -> None: + pass + + def fetchone( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + hard_close: bool = False, + ) -> Any: + return self._non_result(result, None) + + def fetchmany( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + size: Optional[int] = None, + ) -> Any: + return self._non_result(result, []) + + def fetchall( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor + ) -> Any: + return self._non_result(result, []) + + def _non_result( + self, + result: CursorResult[Any], + default: Any, + err: Optional[BaseException] = None, + ) -> Any: + raise NotImplementedError() + + +class NoCursorDQLFetchStrategy(NoCursorFetchStrategy): + """Cursor strategy for a DQL result that has no open cursor. + + This is a result set that can return rows, i.e. for a SELECT, or for an + INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state + where the cursor is closed and no rows remain available. The owning result + object may or may not be "hard closed", which determines if the fetch + methods send empty results or raise for closed result. + + """ + + __slots__ = () + + def _non_result( + self, + result: CursorResult[Any], + default: Any, + err: Optional[BaseException] = None, + ) -> Any: + if result.closed: + raise exc.ResourceClosedError( + "This result object is closed." + ) from err + else: + return default + + +_NO_CURSOR_DQL = NoCursorDQLFetchStrategy() + + +class NoCursorDMLFetchStrategy(NoCursorFetchStrategy): + """Cursor strategy for a DML result that has no open cursor. + + This is a result set that does not return rows, i.e. for an INSERT, + UPDATE, DELETE that does not include RETURNING. + + """ + + __slots__ = () + + def _non_result( + self, + result: CursorResult[Any], + default: Any, + err: Optional[BaseException] = None, + ) -> Any: + # we only expect to have a _NoResultMetaData() here right now. + assert not result._metadata.returns_rows + result._metadata._we_dont_return_rows(err) # type: ignore[union-attr] + + +_NO_CURSOR_DML = NoCursorDMLFetchStrategy() + + +class CursorFetchStrategy(ResultFetchStrategy): + """Call fetch methods from a DBAPI cursor. + + Alternate versions of this class may instead buffer the rows from + cursors or not use cursors at all. + + """ + + __slots__ = () + + def soft_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + result.cursor_strategy = _NO_CURSOR_DQL + + def hard_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + result.cursor_strategy = _NO_CURSOR_DQL + + def handle_exception( + self, + result: CursorResult[Any], + dbapi_cursor: Optional[DBAPICursor], + err: BaseException, + ) -> NoReturn: + result.connection._handle_dbapi_exception( + err, None, None, dbapi_cursor, result.context + ) + + def yield_per( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int + ) -> None: + result.cursor_strategy = BufferedRowCursorFetchStrategy( + dbapi_cursor, + {"max_row_buffer": num}, + initial_buffer=collections.deque(), + growth_factor=0, + ) + + def fetchone( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + hard_close: bool = False, + ) -> Any: + try: + row = dbapi_cursor.fetchone() + if row is None: + result._soft_close(hard=hard_close) + return row + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + + def fetchmany( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + size: Optional[int] = None, + ) -> Any: + try: + if size is None: + l = dbapi_cursor.fetchmany() + else: + l = dbapi_cursor.fetchmany(size) + + if not l: + result._soft_close() + return l + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + + def fetchall( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + ) -> Any: + try: + rows = dbapi_cursor.fetchall() + result._soft_close() + return rows + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + + +_DEFAULT_FETCH = CursorFetchStrategy() + + +class BufferedRowCursorFetchStrategy(CursorFetchStrategy): + """A cursor fetch strategy with row buffering behavior. + + This strategy buffers the contents of a selection of rows + before ``fetchone()`` is called. This is to allow the results of + ``cursor.description`` to be available immediately, when + interfacing with a DB-API that requires rows to be consumed before + this information is available (currently psycopg2, when used with + server-side cursors). + + The pre-fetching behavior fetches only one row initially, and then + grows its buffer size by a fixed amount with each successive need + for additional rows up the ``max_row_buffer`` size, which defaults + to 1000:: + + with psycopg2_engine.connect() as conn: + + result = conn.execution_options( + stream_results=True, max_row_buffer=50 + ).execute(text("select * from table")) + + .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows. + + .. seealso:: + + :ref:`psycopg2_execution_options` + """ + + __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor") + + def __init__( + self, + dbapi_cursor: DBAPICursor, + execution_options: CoreExecuteOptionsParameter, + growth_factor: int = 5, + initial_buffer: Optional[Deque[Any]] = None, + ) -> None: + self._max_row_buffer = execution_options.get("max_row_buffer", 1000) + + if initial_buffer is not None: + self._rowbuffer = initial_buffer + else: + self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1)) + self._growth_factor = growth_factor + + if growth_factor: + self._bufsize = min(self._max_row_buffer, self._growth_factor) + else: + self._bufsize = self._max_row_buffer + + @classmethod + def create( + cls, result: CursorResult[Any] + ) -> BufferedRowCursorFetchStrategy: + return BufferedRowCursorFetchStrategy( + result.cursor, + result.context.execution_options, + ) + + def _buffer_rows( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor + ) -> None: + """this is currently used only by fetchone().""" + + size = self._bufsize + try: + if size < 1: + new_rows = dbapi_cursor.fetchall() + else: + new_rows = dbapi_cursor.fetchmany(size) + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + + if not new_rows: + return + self._rowbuffer = collections.deque(new_rows) + if self._growth_factor and size < self._max_row_buffer: + self._bufsize = min( + self._max_row_buffer, size * self._growth_factor + ) + + def yield_per( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int + ) -> None: + self._growth_factor = 0 + self._max_row_buffer = self._bufsize = num + + def soft_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + self._rowbuffer.clear() + super().soft_close(result, dbapi_cursor) + + def hard_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + self._rowbuffer.clear() + super().hard_close(result, dbapi_cursor) + + def fetchone( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + hard_close: bool = False, + ) -> Any: + if not self._rowbuffer: + self._buffer_rows(result, dbapi_cursor) + if not self._rowbuffer: + try: + result._soft_close(hard=hard_close) + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + return None + return self._rowbuffer.popleft() + + def fetchmany( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + size: Optional[int] = None, + ) -> Any: + if size is None: + return self.fetchall(result, dbapi_cursor) + + rb = self._rowbuffer + lb = len(rb) + close = False + if size > lb: + try: + new = dbapi_cursor.fetchmany(size - lb) + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + else: + if not new: + # defer closing since it may clear the row buffer + close = True + else: + rb.extend(new) + + res = [rb.popleft() for _ in range(min(size, len(rb)))] + if close: + result._soft_close() + return res + + def fetchall( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor + ) -> Any: + try: + ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall()) + self._rowbuffer.clear() + result._soft_close() + return ret + except BaseException as e: + self.handle_exception(result, dbapi_cursor, e) + + +class FullyBufferedCursorFetchStrategy(CursorFetchStrategy): + """A cursor strategy that buffers rows fully upon creation. + + Used for operations where a result is to be delivered + after the database conversation can not be continued, + such as MSSQL INSERT...OUTPUT after an autocommit. + + """ + + __slots__ = ("_rowbuffer", "alternate_cursor_description") + + def __init__( + self, + dbapi_cursor: Optional[DBAPICursor], + alternate_description: Optional[_DBAPICursorDescription] = None, + initial_buffer: Optional[Iterable[Any]] = None, + ): + self.alternate_cursor_description = alternate_description + if initial_buffer is not None: + self._rowbuffer = collections.deque(initial_buffer) + else: + assert dbapi_cursor is not None + self._rowbuffer = collections.deque(dbapi_cursor.fetchall()) + + def yield_per( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int + ) -> Any: + pass + + def soft_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + self._rowbuffer.clear() + super().soft_close(result, dbapi_cursor) + + def hard_close( + self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor] + ) -> None: + self._rowbuffer.clear() + super().hard_close(result, dbapi_cursor) + + def fetchone( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + hard_close: bool = False, + ) -> Any: + if self._rowbuffer: + return self._rowbuffer.popleft() + else: + result._soft_close(hard=hard_close) + return None + + def fetchmany( + self, + result: CursorResult[Any], + dbapi_cursor: DBAPICursor, + size: Optional[int] = None, + ) -> Any: + if size is None: + return self.fetchall(result, dbapi_cursor) + + rb = self._rowbuffer + rows = [rb.popleft() for _ in range(min(size, len(rb)))] + if not rows: + result._soft_close() + return rows + + def fetchall( + self, result: CursorResult[Any], dbapi_cursor: DBAPICursor + ) -> Any: + ret = self._rowbuffer + self._rowbuffer = collections.deque() + result._soft_close() + return ret + + +class _NoResultMetaData(ResultMetaData): + __slots__ = () + + returns_rows = False + + def _we_dont_return_rows( + self, err: Optional[BaseException] = None + ) -> NoReturn: + raise exc.ResourceClosedError( + "This result object does not return rows. " + "It has been closed automatically." + ) from err + + def _index_for_key(self, keys: _KeyIndexType, raiseerr: bool) -> NoReturn: + self._we_dont_return_rows() + + def _metadata_for_keys(self, keys: Sequence[_KeyIndexType]) -> NoReturn: + self._we_dont_return_rows() + + def _reduce(self, keys: Sequence[_KeyIndexType]) -> NoReturn: + self._we_dont_return_rows() + + @property + def _keymap(self) -> NoReturn: # type: ignore[override] + self._we_dont_return_rows() + + @property + def _key_to_index(self) -> NoReturn: # type: ignore[override] + self._we_dont_return_rows() + + @property + def _processors(self) -> NoReturn: # type: ignore[override] + self._we_dont_return_rows() + + @property + def keys(self) -> NoReturn: + self._we_dont_return_rows() + + +_NO_RESULT_METADATA = _NoResultMetaData() + + +def null_dml_result() -> IteratorResult[Any]: + it: IteratorResult[Any] = IteratorResult(_NoResultMetaData(), iter([])) + it._soft_close() + return it + + +class CursorResult(Result[_T]): + """A Result that is representing state from a DBAPI cursor. + + .. versionchanged:: 1.4 The :class:`.CursorResult`` + class replaces the previous :class:`.ResultProxy` interface. + This classes are based on the :class:`.Result` calling API + which provides an updated usage model and calling facade for + SQLAlchemy Core and SQLAlchemy ORM. + + Returns database rows via the :class:`.Row` class, which provides + additional API features and behaviors on top of the raw data returned by + the DBAPI. Through the use of filters such as the :meth:`.Result.scalars` + method, other kinds of objects may also be returned. + + .. seealso:: + + :ref:`tutorial_selecting_data` - introductory material for accessing + :class:`_engine.CursorResult` and :class:`.Row` objects. + + """ + + __slots__ = ( + "context", + "dialect", + "cursor", + "cursor_strategy", + "_echo", + "connection", + ) + + _metadata: Union[CursorResultMetaData, _NoResultMetaData] + _no_result_metadata = _NO_RESULT_METADATA + _soft_closed: bool = False + closed: bool = False + _is_cursor = True + + context: DefaultExecutionContext + dialect: Dialect + cursor_strategy: ResultFetchStrategy + connection: Connection + + def __init__( + self, + context: DefaultExecutionContext, + cursor_strategy: ResultFetchStrategy, + cursor_description: Optional[_DBAPICursorDescription], + ): + self.context = context + self.dialect = context.dialect + self.cursor = context.cursor + self.cursor_strategy = cursor_strategy + self.connection = context.root_connection + self._echo = echo = ( + self.connection._echo and context.engine._should_log_debug() + ) + + if cursor_description is not None: + # inline of Result._row_getter(), set up an initial row + # getter assuming no transformations will be called as this + # is the most common case + + metadata = self._init_metadata(context, cursor_description) + + _make_row: Any + _make_row = functools.partial( + Row, + metadata, + metadata._effective_processors, + metadata._key_to_index, + ) + + if context._num_sentinel_cols: + sentinel_filter = operator.itemgetter( + slice(-context._num_sentinel_cols) + ) + + def _sliced_row(raw_data: Any) -> Any: + return _make_row(sentinel_filter(raw_data)) + + sliced_row = _sliced_row + else: + sliced_row = _make_row + + if echo: + log = self.context.connection._log_debug + + def _log_row(row: Any) -> Any: + log("Row %r", sql_util._repr_row(row)) + return row + + self._row_logging_fn = _log_row + + def _make_row_2(row: Any) -> Any: + return _log_row(sliced_row(row)) + + make_row = _make_row_2 + else: + make_row = sliced_row # type: ignore[assignment] + self._set_memoized_attribute("_row_getter", make_row) + + else: + assert context._num_sentinel_cols == 0 + self._metadata = self._no_result_metadata + + def _init_metadata( + self, + context: DefaultExecutionContext, + cursor_description: _DBAPICursorDescription, + ) -> CursorResultMetaData: + + if context.compiled: + compiled = context.compiled + + if compiled._cached_metadata: + metadata = compiled._cached_metadata + else: + metadata = CursorResultMetaData(self, cursor_description) + if metadata._safe_for_cache: + compiled._cached_metadata = metadata + + # result rewrite/ adapt step. this is to suit the case + # when we are invoked against a cached Compiled object, we want + # to rewrite the ResultMetaData to reflect the Column objects + # that are in our current SQL statement object, not the one + # that is associated with the cached Compiled object. + # the Compiled object may also tell us to not + # actually do this step; this is to support the ORM where + # it is to produce a new Result object in any case, and will + # be using the cached Column objects against this database result + # so we don't want to rewrite them. + # + # Basically this step suits the use case where the end user + # is using Core SQL expressions and is accessing columns in the + # result row using row._mapping[table.c.column]. + if ( + not context.execution_options.get( + "_result_disable_adapt_to_context", False + ) + and compiled._result_columns + and context.cache_hit is context.dialect.CACHE_HIT + and compiled.statement is not context.invoked_statement # type: ignore[comparison-overlap] # noqa: E501 + ): + metadata = metadata._adapt_to_context(context) # type: ignore[assignment] # noqa: E501 + + self._metadata = metadata + + else: + self._metadata = metadata = CursorResultMetaData( + self, cursor_description + ) + if self._echo: + context.connection._log_debug( + "Col %r", tuple(x[0] for x in cursor_description) + ) + return metadata + + def _soft_close(self, hard: bool = False) -> None: + """Soft close this :class:`_engine.CursorResult`. + + This releases all DBAPI cursor resources, but leaves the + CursorResult "open" from a semantic perspective, meaning the + fetchXXX() methods will continue to return empty results. + + This method is called automatically when: + + * all result rows are exhausted using the fetchXXX() methods. + * cursor.description is None. + + This method is **not public**, but is documented in order to clarify + the "autoclose" process used. + + .. seealso:: + + :meth:`_engine.CursorResult.close` + + + """ + + if (not hard and self._soft_closed) or (hard and self.closed): + return + + if hard: + self.closed = True + self.cursor_strategy.hard_close(self, self.cursor) + else: + self.cursor_strategy.soft_close(self, self.cursor) + + if not self._soft_closed: + cursor = self.cursor + self.cursor = None # type: ignore + self.connection._safe_close_cursor(cursor) + self._soft_closed = True + + @property + def inserted_primary_key_rows(self) -> List[Optional[Any]]: + """Return the value of + :attr:`_engine.CursorResult.inserted_primary_key` + as a row contained within a list; some dialects may support a + multiple row form as well. + + .. note:: As indicated below, in current SQLAlchemy versions this + accessor is only useful beyond what's already supplied by + :attr:`_engine.CursorResult.inserted_primary_key` when using the + :ref:`postgresql_psycopg2` dialect. Future versions hope to + generalize this feature to more dialects. + + This accessor is added to support dialects that offer the feature + that is currently implemented by the :ref:`psycopg2_executemany_mode` + feature, currently **only the psycopg2 dialect**, which provides + for many rows to be INSERTed at once while still retaining the + behavior of being able to return server-generated primary key values. + + * **When using the psycopg2 dialect, or other dialects that may support + "fast executemany" style inserts in upcoming releases** : When + invoking an INSERT statement while passing a list of rows as the + second argument to :meth:`_engine.Connection.execute`, this accessor + will then provide a list of rows, where each row contains the primary + key value for each row that was INSERTed. + + * **When using all other dialects / backends that don't yet support + this feature**: This accessor is only useful for **single row INSERT + statements**, and returns the same information as that of the + :attr:`_engine.CursorResult.inserted_primary_key` within a + single-element list. When an INSERT statement is executed in + conjunction with a list of rows to be INSERTed, the list will contain + one row per row inserted in the statement, however it will contain + ``None`` for any server-generated values. + + Future releases of SQLAlchemy will further generalize the + "fast execution helper" feature of psycopg2 to suit other dialects, + thus allowing this accessor to be of more general use. + + .. versionadded:: 1.4 + + .. seealso:: + + :attr:`_engine.CursorResult.inserted_primary_key` + + """ + if not self.context.compiled: + raise exc.InvalidRequestError( + "Statement is not a compiled expression construct." + ) + elif not self.context.isinsert: + raise exc.InvalidRequestError( + "Statement is not an insert() expression construct." + ) + elif self.context._is_explicit_returning: + raise exc.InvalidRequestError( + "Can't call inserted_primary_key " + "when returning() " + "is used." + ) + return self.context.inserted_primary_key_rows # type: ignore[no-any-return] # noqa: E501 + + @property + def inserted_primary_key(self) -> Optional[Any]: + """Return the primary key for the row just inserted. + + The return value is a :class:`_result.Row` object representing + a named tuple of primary key values in the order in which the + primary key columns are configured in the source + :class:`_schema.Table`. + + .. versionchanged:: 1.4.8 - the + :attr:`_engine.CursorResult.inserted_primary_key` + value is now a named tuple via the :class:`_result.Row` class, + rather than a plain tuple. + + This accessor only applies to single row :func:`_expression.insert` + constructs which did not explicitly specify + :meth:`_expression.Insert.returning`. Support for multirow inserts, + while not yet available for most backends, would be accessed using + the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor. + + Note that primary key columns which specify a server_default clause, or + otherwise do not qualify as "autoincrement" columns (see the notes at + :class:`_schema.Column`), and were generated using the database-side + default, will appear in this list as ``None`` unless the backend + supports "returning" and the insert statement executed with the + "implicit returning" enabled. + + Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed + statement is not a compiled expression construct + or is not an insert() construct. + + """ + + if self.context.executemany: + raise exc.InvalidRequestError( + "This statement was an executemany call; if primary key " + "returning is supported, please " + "use .inserted_primary_key_rows." + ) + + ikp = self.inserted_primary_key_rows + if ikp: + return ikp[0] + else: + return None + + def last_updated_params( + self, + ) -> Union[ + List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams + ]: + """Return the collection of updated parameters from this + execution. + + Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed + statement is not a compiled expression construct + or is not an update() construct. + + """ + if not self.context.compiled: + raise exc.InvalidRequestError( + "Statement is not a compiled expression construct." + ) + elif not self.context.isupdate: + raise exc.InvalidRequestError( + "Statement is not an update() expression construct." + ) + elif self.context.executemany: + return self.context.compiled_parameters + else: + return self.context.compiled_parameters[0] + + def last_inserted_params( + self, + ) -> Union[ + List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams + ]: + """Return the collection of inserted parameters from this + execution. + + Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed + statement is not a compiled expression construct + or is not an insert() construct. + + """ + if not self.context.compiled: + raise exc.InvalidRequestError( + "Statement is not a compiled expression construct." + ) + elif not self.context.isinsert: + raise exc.InvalidRequestError( + "Statement is not an insert() expression construct." + ) + elif self.context.executemany: + return self.context.compiled_parameters + else: + return self.context.compiled_parameters[0] + + @property + def returned_defaults_rows( + self, + ) -> Optional[Sequence[Row[Any]]]: + """Return a list of rows each containing the values of default + columns that were fetched using + the :meth:`.ValuesBase.return_defaults` feature. + + The return value is a list of :class:`.Row` objects. + + .. versionadded:: 1.4 + + """ + return self.context.returned_default_rows + + def splice_horizontally(self, other: CursorResult[Any]) -> Self: + """Return a new :class:`.CursorResult` that "horizontally splices" + together the rows of this :class:`.CursorResult` with that of another + :class:`.CursorResult`. + + .. tip:: This method is for the benefit of the SQLAlchemy ORM and is + not intended for general use. + + "horizontally splices" means that for each row in the first and second + result sets, a new row that concatenates the two rows together is + produced, which then becomes the new row. The incoming + :class:`.CursorResult` must have the identical number of rows. It is + typically expected that the two result sets come from the same sort + order as well, as the result rows are spliced together based on their + position in the result. + + The expected use case here is so that multiple INSERT..RETURNING + statements (which definitely need to be sorted) against different + tables can produce a single result that looks like a JOIN of those two + tables. + + E.g.:: + + r1 = connection.execute( + users.insert().returning( + users.c.user_name, users.c.user_id, sort_by_parameter_order=True + ), + user_values, + ) + + r2 = connection.execute( + addresses.insert().returning( + addresses.c.address_id, + addresses.c.address, + addresses.c.user_id, + sort_by_parameter_order=True, + ), + address_values, + ) + + rows = r1.splice_horizontally(r2).all() + assert rows == [ + ("john", 1, 1, "foo@bar.com", 1), + ("jack", 2, 2, "bar@bat.com", 2), + ] + + .. versionadded:: 2.0 + + .. seealso:: + + :meth:`.CursorResult.splice_vertically` + + + """ # noqa: E501 + + clone = self._generate() + total_rows = [ + tuple(r1) + tuple(r2) + for r1, r2 in zip( + list(self._raw_row_iterator()), + list(other._raw_row_iterator()), + ) + ] + + clone._metadata = clone._metadata._splice_horizontally(other._metadata) # type: ignore[union-attr, arg-type] # noqa: E501 + + clone.cursor_strategy = FullyBufferedCursorFetchStrategy( + None, + initial_buffer=total_rows, + ) + clone._reset_memoizations() + return clone + + def splice_vertically(self, other: CursorResult[Any]) -> Self: + """Return a new :class:`.CursorResult` that "vertically splices", + i.e. "extends", the rows of this :class:`.CursorResult` with that of + another :class:`.CursorResult`. + + .. tip:: This method is for the benefit of the SQLAlchemy ORM and is + not intended for general use. + + "vertically splices" means the rows of the given result are appended to + the rows of this cursor result. The incoming :class:`.CursorResult` + must have rows that represent the identical list of columns in the + identical order as they are in this :class:`.CursorResult`. + + .. versionadded:: 2.0 + + .. seealso:: + + :meth:`.CursorResult.splice_horizontally` + + """ + clone = self._generate() + total_rows = list(self._raw_row_iterator()) + list( + other._raw_row_iterator() + ) + + clone.cursor_strategy = FullyBufferedCursorFetchStrategy( + None, + initial_buffer=total_rows, + ) + clone._reset_memoizations() + return clone + + def _rewind(self, rows: Any) -> Self: + """rewind this result back to the given rowset. + + this is used internally for the case where an :class:`.Insert` + construct combines the use of + :meth:`.Insert.return_defaults` along with the + "supplemental columns" feature. + + """ + + if self._echo: + self.context.connection._log_debug( + "CursorResult rewound %d row(s)", len(rows) + ) + + # the rows given are expected to be Row objects, so we + # have to clear out processors which have already run on these + # rows + self._metadata = cast( + CursorResultMetaData, self._metadata + )._remove_processors() + + self.cursor_strategy = FullyBufferedCursorFetchStrategy( + None, + # TODO: if these are Row objects, can we save on not having to + # re-make new Row objects out of them a second time? is that + # what's actually happening right now? maybe look into this + initial_buffer=rows, + ) + self._reset_memoizations() + return self + + @property + def returned_defaults(self) -> Optional[Row[Any]]: + """Return the values of default columns that were fetched using + the :meth:`.ValuesBase.return_defaults` feature. + + The value is an instance of :class:`.Row`, or ``None`` + if :meth:`.ValuesBase.return_defaults` was not used or if the + backend does not support RETURNING. + + .. seealso:: + + :meth:`.ValuesBase.return_defaults` + + """ + + if self.context.executemany: + raise exc.InvalidRequestError( + "This statement was an executemany call; if return defaults " + "is supported, please use .returned_defaults_rows." + ) + + rows = self.context.returned_default_rows + if rows: + return rows[0] + else: + return None + + def lastrow_has_defaults(self) -> bool: + """Return ``lastrow_has_defaults()`` from the underlying + :class:`.ExecutionContext`. + + See :class:`.ExecutionContext` for details. + + """ + + return self.context.lastrow_has_defaults() + + def postfetch_cols(self) -> Optional[Sequence[Column[Any]]]: + """Return ``postfetch_cols()`` from the underlying + :class:`.ExecutionContext`. + + See :class:`.ExecutionContext` for details. + + Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed + statement is not a compiled expression construct + or is not an insert() or update() construct. + + """ + + if not self.context.compiled: + raise exc.InvalidRequestError( + "Statement is not a compiled expression construct." + ) + elif not self.context.isinsert and not self.context.isupdate: + raise exc.InvalidRequestError( + "Statement is not an insert() or update() " + "expression construct." + ) + return self.context.postfetch_cols + + def prefetch_cols(self) -> Optional[Sequence[Column[Any]]]: + """Return ``prefetch_cols()`` from the underlying + :class:`.ExecutionContext`. + + See :class:`.ExecutionContext` for details. + + Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed + statement is not a compiled expression construct + or is not an insert() or update() construct. + + """ + + if not self.context.compiled: + raise exc.InvalidRequestError( + "Statement is not a compiled expression construct." + ) + elif not self.context.isinsert and not self.context.isupdate: + raise exc.InvalidRequestError( + "Statement is not an insert() or update() " + "expression construct." + ) + return self.context.prefetch_cols + + def supports_sane_rowcount(self) -> bool: + """Return ``supports_sane_rowcount`` from the dialect. + + See :attr:`_engine.CursorResult.rowcount` for background. + + """ + + return self.dialect.supports_sane_rowcount + + def supports_sane_multi_rowcount(self) -> bool: + """Return ``supports_sane_multi_rowcount`` from the dialect. + + See :attr:`_engine.CursorResult.rowcount` for background. + + """ + + return self.dialect.supports_sane_multi_rowcount + + @util.memoized_property + def rowcount(self) -> int: + """Return the 'rowcount' for this result. + + The primary purpose of 'rowcount' is to report the number of rows + matched by the WHERE criterion of an UPDATE or DELETE statement + executed once (i.e. for a single parameter set), which may then be + compared to the number of rows expected to be updated or deleted as a + means of asserting data integrity. + + This attribute is transferred from the ``cursor.rowcount`` attribute + of the DBAPI before the cursor is closed, to support DBAPIs that + don't make this value available after cursor close. Some DBAPIs may + offer meaningful values for other kinds of statements, such as INSERT + and SELECT statements as well. In order to retrieve ``cursor.rowcount`` + for these statements, set the + :paramref:`.Connection.execution_options.preserve_rowcount` + execution option to True, which will cause the ``cursor.rowcount`` + value to be unconditionally memoized before any results are returned + or the cursor is closed, regardless of statement type. + + For cases where the DBAPI does not support rowcount for a particular + kind of statement and/or execution, the returned value will be ``-1``, + which is delivered directly from the DBAPI and is part of :pep:`249`. + All DBAPIs should support rowcount for single-parameter-set + UPDATE and DELETE statements, however. + + .. note:: + + Notes regarding :attr:`_engine.CursorResult.rowcount`: + + + * This attribute returns the number of rows *matched*, + which is not necessarily the same as the number of rows + that were actually *modified*. For example, an UPDATE statement + may have no net change on a given row if the SET values + given are the same as those present in the row already. + Such a row would be matched but not modified. + On backends that feature both styles, such as MySQL, + rowcount is configured to return the match + count in all cases. + + * :attr:`_engine.CursorResult.rowcount` in the default case is + *only* useful in conjunction with an UPDATE or DELETE statement, + and only with a single set of parameters. For other kinds of + statements, SQLAlchemy will not attempt to pre-memoize the value + unless the + :paramref:`.Connection.execution_options.preserve_rowcount` + execution option is used. Note that contrary to :pep:`249`, many + DBAPIs do not support rowcount values for statements that are not + UPDATE or DELETE, particularly when rows are being returned which + are not fully pre-buffered. DBAPIs that dont support rowcount + for a particular kind of statement should return the value ``-1`` + for such statements. + + * :attr:`_engine.CursorResult.rowcount` may not be meaningful + when executing a single statement with multiple parameter sets + (i.e. an :term:`executemany`). Most DBAPIs do not sum "rowcount" + values across multiple parameter sets and will return ``-1`` + when accessed. + + * SQLAlchemy's :ref:`engine_insertmanyvalues` feature does support + a correct population of :attr:`_engine.CursorResult.rowcount` + when the :paramref:`.Connection.execution_options.preserve_rowcount` + execution option is set to True. + + * Statements that use RETURNING may not support rowcount, returning + a ``-1`` value instead. + + .. seealso:: + + :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial` + + :paramref:`.Connection.execution_options.preserve_rowcount` + + """ # noqa: E501 + try: + return self.context.rowcount + except BaseException as e: + self.cursor_strategy.handle_exception(self, self.cursor, e) + raise # not called + + @property + def lastrowid(self) -> int: + """Return the 'lastrowid' accessor on the DBAPI cursor. + + This is a DBAPI specific method and is only functional + for those backends which support it, for statements + where it is appropriate. It's behavior is not + consistent across backends. + + Usage of this method is normally unnecessary when + using insert() expression constructs; the + :attr:`~CursorResult.inserted_primary_key` attribute provides a + tuple of primary key values for a newly inserted row, + regardless of database backend. + + """ + try: + return self.context.get_lastrowid() + except BaseException as e: + self.cursor_strategy.handle_exception(self, self.cursor, e) + + @property + def returns_rows(self) -> bool: + """True if this :class:`_engine.CursorResult` returns zero or more + rows. + + I.e. if it is legal to call the methods + :meth:`_engine.CursorResult.fetchone`, + :meth:`_engine.CursorResult.fetchmany` + :meth:`_engine.CursorResult.fetchall`. + + Overall, the value of :attr:`_engine.CursorResult.returns_rows` should + always be synonymous with whether or not the DBAPI cursor had a + ``.description`` attribute, indicating the presence of result columns, + noting that a cursor that returns zero rows still has a + ``.description`` if a row-returning statement was emitted. + + This attribute should be True for all results that are against + SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE + that use RETURNING. For INSERT/UPDATE/DELETE statements that were + not using RETURNING, the value will usually be False, however + there are some dialect-specific exceptions to this, such as when + using the MSSQL / pyodbc dialect a SELECT is emitted inline in + order to retrieve an inserted primary key value. + + .. seealso:: + + :meth:`.Result.close` + + :attr:`.Result.closed` + + """ + return self._metadata.returns_rows + + @property + def is_insert(self) -> bool: + """True if this :class:`_engine.CursorResult` is the result + of a executing an expression language compiled + :func:`_expression.insert` construct. + + When True, this implies that the + :attr:`inserted_primary_key` attribute is accessible, + assuming the statement did not include + a user defined "returning" construct. + + """ + return self.context.isinsert + + def _fetchiter_impl(self) -> Iterator[Any]: + fetchone = self.cursor_strategy.fetchone + + while True: + row = fetchone(self, self.cursor) + if row is None: + break + yield row + + def _fetchone_impl(self, hard_close: bool = False) -> Any: + return self.cursor_strategy.fetchone(self, self.cursor, hard_close) + + def _fetchall_impl(self) -> Any: + return self.cursor_strategy.fetchall(self, self.cursor) + + def _fetchmany_impl(self, size: Optional[int] = None) -> Any: + return self.cursor_strategy.fetchmany(self, self.cursor, size) + + def _raw_row_iterator(self) -> Any: + return self._fetchiter_impl() + + def merge(self, *others: Result[Any]) -> MergedResult[Any]: + merged_result = super().merge(*others) + if self.context._has_rowcount: + merged_result.rowcount = sum( + cast("CursorResult[Any]", result).rowcount + for result in (self,) + others + ) + return merged_result + + def close(self) -> None: + """Close this :class:`_engine.CursorResult`. + + This closes out the underlying DBAPI cursor corresponding to the + statement execution, if one is still present. Note that the DBAPI + cursor is automatically released when the :class:`_engine.CursorResult` + exhausts all available rows. :meth:`_engine.CursorResult.close` is + generally an optional method except in the case when discarding a + :class:`_engine.CursorResult` that still has additional rows pending + for fetch. + + After this method is called, it is no longer valid to call upon + the fetch methods, which will raise a :class:`.ResourceClosedError` + on subsequent use. + + .. seealso:: + + :ref:`connections_toplevel` + + """ + self._soft_close(hard=True) + + @_generative + def yield_per(self, num: int) -> Self: + self._yield_per = num + self.cursor_strategy.yield_per(self, self.cursor, num) + return self + + +ResultProxy = CursorResult diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/default.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/default.py new file mode 100644 index 0000000000000000000000000000000000000000..20be420fa5d15610c4305f601ac41c881cb6913c --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/default.py @@ -0,0 +1,2394 @@ +# engine/default.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: allow-untyped-defs, allow-untyped-calls + +"""Default implementations of per-dialect sqlalchemy.engine classes. + +These are semi-private implementation classes which are only of importance +to database dialect authors; dialects will usually use the classes here +as the base class for their own corresponding classes. + +""" + +from __future__ import annotations + +import functools +import operator +import random +import re +from time import perf_counter +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import MutableSequence +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import Union +import weakref + +from . import characteristics +from . import cursor as _cursor +from . import interfaces +from .base import Connection +from .interfaces import CacheStats +from .interfaces import DBAPICursor +from .interfaces import Dialect +from .interfaces import ExecuteStyle +from .interfaces import ExecutionContext +from .reflection import ObjectKind +from .reflection import ObjectScope +from .. import event +from .. import exc +from .. import pool +from .. import util +from ..sql import compiler +from ..sql import dml +from ..sql import expression +from ..sql import type_api +from ..sql import util as sql_util +from ..sql._typing import is_tuple_type +from ..sql.base import _NoArg +from ..sql.compiler import DDLCompiler +from ..sql.compiler import InsertmanyvaluesSentinelOpts +from ..sql.compiler import SQLCompiler +from ..sql.elements import quoted_name +from ..util.typing import Final +from ..util.typing import Literal + +if typing.TYPE_CHECKING: + from types import ModuleType + + from .base import Engine + from .cursor import ResultFetchStrategy + from .interfaces import _CoreMultiExecuteParams + from .interfaces import _CoreSingleExecuteParams + from .interfaces import _DBAPICursorDescription + from .interfaces import _DBAPIMultiExecuteParams + from .interfaces import _DBAPISingleExecuteParams + from .interfaces import _ExecuteOptions + from .interfaces import _MutableCoreSingleExecuteParams + from .interfaces import _ParamStyle + from .interfaces import ConnectArgsType + from .interfaces import DBAPIConnection + from .interfaces import DBAPIModule + from .interfaces import DBAPIType + from .interfaces import IsolationLevel + from .row import Row + from .url import URL + from ..event import _ListenerFnType + from ..pool import Pool + from ..pool import PoolProxiedConnection + from ..sql import Executable + from ..sql.compiler import Compiled + from ..sql.compiler import Linting + from ..sql.compiler import ResultColumnsEntry + from ..sql.dml import DMLState + from ..sql.dml import UpdateBase + from ..sql.elements import BindParameter + from ..sql.schema import Column + from ..sql.type_api import _BindProcessorType + from ..sql.type_api import _ResultProcessorType + from ..sql.type_api import TypeEngine + + +# When we're handed literal SQL, ensure it's a SELECT query +SERVER_SIDE_CURSOR_RE = re.compile(r"\s*SELECT", re.I | re.UNICODE) + + +( + CACHE_HIT, + CACHE_MISS, + CACHING_DISABLED, + NO_CACHE_KEY, + NO_DIALECT_SUPPORT, +) = list(CacheStats) + + +class DefaultDialect(Dialect): + """Default implementation of Dialect""" + + statement_compiler = compiler.SQLCompiler + ddl_compiler = compiler.DDLCompiler + type_compiler_cls = compiler.GenericTypeCompiler + + preparer = compiler.IdentifierPreparer + supports_alter = True + supports_comments = False + supports_constraint_comments = False + inline_comments = False + supports_statement_cache = True + + div_is_floordiv = True + + bind_typing = interfaces.BindTyping.NONE + + include_set_input_sizes: Optional[Set[Any]] = None + exclude_set_input_sizes: Optional[Set[Any]] = None + + # the first value we'd get for an autoincrement column. + default_sequence_base = 1 + + # most DBAPIs happy with this for execute(). + # not cx_oracle. + execute_sequence_format = tuple + + supports_schemas = True + supports_views = True + supports_sequences = False + sequences_optional = False + preexecute_autoincrement_sequences = False + supports_identity_columns = False + postfetch_lastrowid = True + favor_returning_over_lastrowid = False + insert_null_pk_still_autoincrements = False + update_returning = False + delete_returning = False + update_returning_multifrom = False + delete_returning_multifrom = False + insert_returning = False + + cte_follows_insert = False + + supports_native_enum = False + supports_native_boolean = False + supports_native_uuid = False + returns_native_bytes = False + + non_native_boolean_check_constraint = True + + supports_simple_order_by_label = True + + tuple_in_values = False + + connection_characteristics = util.immutabledict( + { + "isolation_level": characteristics.IsolationLevelCharacteristic(), + "logging_token": characteristics.LoggingTokenCharacteristic(), + } + ) + + engine_config_types: Mapping[str, Any] = util.immutabledict( + { + "pool_timeout": util.asint, + "echo": util.bool_or_str("debug"), + "echo_pool": util.bool_or_str("debug"), + "pool_recycle": util.asint, + "pool_size": util.asint, + "max_overflow": util.asint, + "future": util.asbool, + } + ) + + # if the NUMERIC type + # returns decimal.Decimal. + # *not* the FLOAT type however. + supports_native_decimal = False + + name = "default" + + # length at which to truncate + # any identifier. + max_identifier_length = 9999 + _user_defined_max_identifier_length: Optional[int] = None + + isolation_level: Optional[str] = None + + # sub-categories of max_identifier_length. + # currently these accommodate for MySQL which allows alias names + # of 255 but DDL names only of 64. + max_index_name_length: Optional[int] = None + max_constraint_name_length: Optional[int] = None + + supports_sane_rowcount = True + supports_sane_multi_rowcount = True + colspecs: MutableMapping[Type[TypeEngine[Any]], Type[TypeEngine[Any]]] = {} + default_paramstyle = "named" + + supports_default_values = False + """dialect supports INSERT... DEFAULT VALUES syntax""" + + supports_default_metavalue = False + """dialect supports INSERT... VALUES (DEFAULT) syntax""" + + default_metavalue_token = "DEFAULT" + """for INSERT... VALUES (DEFAULT) syntax, the token to put in the + parenthesis.""" + + # not sure if this is a real thing but the compiler will deliver it + # if this is the only flag enabled. + supports_empty_insert = True + """dialect supports INSERT () VALUES ()""" + + supports_multivalues_insert = False + + use_insertmanyvalues: bool = False + + use_insertmanyvalues_wo_returning: bool = False + + insertmanyvalues_implicit_sentinel: InsertmanyvaluesSentinelOpts = ( + InsertmanyvaluesSentinelOpts.NOT_SUPPORTED + ) + + insertmanyvalues_page_size: int = 1000 + insertmanyvalues_max_parameters = 32700 + + supports_is_distinct_from = True + + supports_server_side_cursors = False + + server_side_cursors = False + + # extra record-level locking features (#4860) + supports_for_update_of = False + + server_version_info = None + + default_schema_name: Optional[str] = None + + # indicates symbol names are + # UPPERCASED if they are case insensitive + # within the database. + # if this is True, the methods normalize_name() + # and denormalize_name() must be provided. + requires_name_normalize = False + + is_async = False + + has_terminate = False + + # TODO: this is not to be part of 2.0. implement rudimentary binary + # literals for SQLite, PostgreSQL, MySQL only within + # _Binary.literal_processor + _legacy_binary_type_literal_encoding = "utf-8" + + @util.deprecated_params( + empty_in_strategy=( + "1.4", + "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is " + "deprecated, and no longer has any effect. All IN expressions " + "are now rendered using " + 'the "expanding parameter" strategy which renders a set of bound' + 'expressions, or an "empty set" SELECT, at statement execution' + "time.", + ), + server_side_cursors=( + "1.4", + "The :paramref:`_sa.create_engine.server_side_cursors` parameter " + "is deprecated and will be removed in a future release. Please " + "use the " + ":paramref:`_engine.Connection.execution_options.stream_results` " + "parameter.", + ), + ) + def __init__( + self, + paramstyle: Optional[_ParamStyle] = None, + isolation_level: Optional[IsolationLevel] = None, + dbapi: Optional[ModuleType] = None, + implicit_returning: Literal[True] = True, + supports_native_boolean: Optional[bool] = None, + max_identifier_length: Optional[int] = None, + label_length: Optional[int] = None, + insertmanyvalues_page_size: Union[_NoArg, int] = _NoArg.NO_ARG, + use_insertmanyvalues: Optional[bool] = None, + # util.deprecated_params decorator cannot render the + # Linting.NO_LINTING constant + compiler_linting: Linting = int(compiler.NO_LINTING), # type: ignore + server_side_cursors: bool = False, + skip_autocommit_rollback: bool = False, + **kwargs: Any, + ): + if server_side_cursors: + if not self.supports_server_side_cursors: + raise exc.ArgumentError( + "Dialect %s does not support server side cursors" % self + ) + else: + self.server_side_cursors = True + + if getattr(self, "use_setinputsizes", False): + util.warn_deprecated( + "The dialect-level use_setinputsizes attribute is " + "deprecated. Please use " + "bind_typing = BindTyping.SETINPUTSIZES", + "2.0", + ) + self.bind_typing = interfaces.BindTyping.SETINPUTSIZES + + self.positional = False + self._ischema = None + + self.dbapi = dbapi + + self.skip_autocommit_rollback = skip_autocommit_rollback + + if paramstyle is not None: + self.paramstyle = paramstyle + elif self.dbapi is not None: + self.paramstyle = self.dbapi.paramstyle + else: + self.paramstyle = self.default_paramstyle + self.positional = self.paramstyle in ( + "qmark", + "format", + "numeric", + "numeric_dollar", + ) + self.identifier_preparer = self.preparer(self) + self._on_connect_isolation_level = isolation_level + + legacy_tt_callable = getattr(self, "type_compiler", None) + if legacy_tt_callable is not None: + tt_callable = cast( + Type[compiler.GenericTypeCompiler], + self.type_compiler, + ) + else: + tt_callable = self.type_compiler_cls + + self.type_compiler_instance = self.type_compiler = tt_callable(self) + + if supports_native_boolean is not None: + self.supports_native_boolean = supports_native_boolean + + self._user_defined_max_identifier_length = max_identifier_length + if self._user_defined_max_identifier_length: + self.max_identifier_length = ( + self._user_defined_max_identifier_length + ) + self.label_length = label_length + self.compiler_linting = compiler_linting + + if use_insertmanyvalues is not None: + self.use_insertmanyvalues = use_insertmanyvalues + + if insertmanyvalues_page_size is not _NoArg.NO_ARG: + self.insertmanyvalues_page_size = insertmanyvalues_page_size + + @property + @util.deprecated( + "2.0", + "full_returning is deprecated, please use insert_returning, " + "update_returning, delete_returning", + ) + def full_returning(self): + return ( + self.insert_returning + and self.update_returning + and self.delete_returning + ) + + @util.memoized_property + def insert_executemany_returning(self): + """Default implementation for insert_executemany_returning, if not + otherwise overridden by the specific dialect. + + The default dialect determines "insert_executemany_returning" is + available if the dialect in use has opted into using the + "use_insertmanyvalues" feature. If they haven't opted into that, then + this attribute is False, unless the dialect in question overrides this + and provides some other implementation (such as the Oracle Database + dialects). + + """ + return self.insert_returning and self.use_insertmanyvalues + + @util.memoized_property + def insert_executemany_returning_sort_by_parameter_order(self): + """Default implementation for + insert_executemany_returning_deterministic_order, if not otherwise + overridden by the specific dialect. + + The default dialect determines "insert_executemany_returning" can have + deterministic order only if the dialect in use has opted into using the + "use_insertmanyvalues" feature, which implements deterministic ordering + using client side sentinel columns only by default. The + "insertmanyvalues" feature also features alternate forms that can + use server-generated PK values as "sentinels", but those are only + used if the :attr:`.Dialect.insertmanyvalues_implicit_sentinel` + bitflag enables those alternate SQL forms, which are disabled + by default. + + If the dialect in use hasn't opted into that, then this attribute is + False, unless the dialect in question overrides this and provides some + other implementation (such as the Oracle Database dialects). + + """ + return self.insert_returning and self.use_insertmanyvalues + + update_executemany_returning = False + delete_executemany_returning = False + + @util.memoized_property + def loaded_dbapi(self) -> DBAPIModule: + if self.dbapi is None: + raise exc.InvalidRequestError( + f"Dialect {self} does not have a Python DBAPI established " + "and cannot be used for actual database interaction" + ) + return self.dbapi + + @util.memoized_property + def _bind_typing_render_casts(self): + return self.bind_typing is interfaces.BindTyping.RENDER_CASTS + + def _ensure_has_table_connection(self, arg: Connection) -> None: + if not isinstance(arg, Connection): + raise exc.ArgumentError( + "The argument passed to Dialect.has_table() should be a " + "%s, got %s. " + "Additionally, the Dialect.has_table() method is for " + "internal dialect " + "use only; please use " + "``inspect(some_engine).has_table(>)`` " + "for public API use." % (Connection, type(arg)) + ) + + @util.memoized_property + def _supports_statement_cache(self): + ssc = self.__class__.__dict__.get("supports_statement_cache", None) + if ssc is None: + util.warn( + "Dialect %s:%s will not make use of SQL compilation caching " + "as it does not set the 'supports_statement_cache' attribute " + "to ``True``. This can have " + "significant performance implications including some " + "performance degradations in comparison to prior SQLAlchemy " + "versions. Dialect maintainers should seek to set this " + "attribute to True after appropriate development and testing " + "for SQLAlchemy 1.4 caching support. Alternatively, this " + "attribute may be set to False which will disable this " + "warning." % (self.name, self.driver), + code="cprf", + ) + + return bool(ssc) + + @util.memoized_property + def _type_memos(self): + return weakref.WeakKeyDictionary() + + @property + def dialect_description(self): # type: ignore[override] + return self.name + "+" + self.driver + + @property + def supports_sane_rowcount_returning(self): + """True if this dialect supports sane rowcount even if RETURNING is + in use. + + For dialects that don't support RETURNING, this is synonymous with + ``supports_sane_rowcount``. + + """ + return self.supports_sane_rowcount + + @classmethod + def get_pool_class(cls, url: URL) -> Type[Pool]: + return getattr(cls, "poolclass", pool.QueuePool) + + def get_dialect_pool_class(self, url: URL) -> Type[Pool]: + return self.get_pool_class(url) + + @classmethod + def load_provisioning(cls): + package = ".".join(cls.__module__.split(".")[0:-1]) + try: + __import__(package + ".provision") + except ImportError: + pass + + def _builtin_onconnect(self) -> Optional[_ListenerFnType]: + if self._on_connect_isolation_level is not None: + + def builtin_connect(dbapi_conn, conn_rec): + self._assert_and_set_isolation_level( + dbapi_conn, self._on_connect_isolation_level + ) + + return builtin_connect + else: + return None + + def initialize(self, connection: Connection) -> None: + try: + self.server_version_info = self._get_server_version_info( + connection + ) + except NotImplementedError: + self.server_version_info = None + try: + self.default_schema_name = self._get_default_schema_name( + connection + ) + except NotImplementedError: + self.default_schema_name = None + + try: + self.default_isolation_level = self.get_default_isolation_level( + connection.connection.dbapi_connection + ) + except NotImplementedError: + self.default_isolation_level = None + + if not self._user_defined_max_identifier_length: + max_ident_length = self._check_max_identifier_length(connection) + if max_ident_length: + self.max_identifier_length = max_ident_length + + if ( + self.label_length + and self.label_length > self.max_identifier_length + ): + raise exc.ArgumentError( + "Label length of %d is greater than this dialect's" + " maximum identifier length of %d" + % (self.label_length, self.max_identifier_length) + ) + + def on_connect(self) -> Optional[Callable[[Any], None]]: + # inherits the docstring from interfaces.Dialect.on_connect + return None + + def _check_max_identifier_length(self, connection): + """Perform a connection / server version specific check to determine + the max_identifier_length. + + If the dialect's class level max_identifier_length should be used, + can return None. + + .. versionadded:: 1.3.9 + + """ + return None + + def get_default_isolation_level(self, dbapi_conn): + """Given a DBAPI connection, return its isolation level, or + a default isolation level if one cannot be retrieved. + + May be overridden by subclasses in order to provide a + "fallback" isolation level for databases that cannot reliably + retrieve the actual isolation level. + + By default, calls the :meth:`_engine.Interfaces.get_isolation_level` + method, propagating any exceptions raised. + + .. versionadded:: 1.3.22 + + """ + return self.get_isolation_level(dbapi_conn) + + def type_descriptor(self, typeobj): + """Provide a database-specific :class:`.TypeEngine` object, given + the generic object which comes from the types module. + + This method looks for a dictionary called + ``colspecs`` as a class or instance-level variable, + and passes on to :func:`_types.adapt_type`. + + """ + return type_api.adapt_type(typeobj, self.colspecs) + + def has_index(self, connection, table_name, index_name, schema=None, **kw): + if not self.has_table(connection, table_name, schema=schema, **kw): + return False + for idx in self.get_indexes( + connection, table_name, schema=schema, **kw + ): + if idx["name"] == index_name: + return True + else: + return False + + def has_schema( + self, connection: Connection, schema_name: str, **kw: Any + ) -> bool: + return schema_name in self.get_schema_names(connection, **kw) + + def validate_identifier(self, ident: str) -> None: + if len(ident) > self.max_identifier_length: + raise exc.IdentifierError( + "Identifier '%s' exceeds maximum length of %d characters" + % (ident, self.max_identifier_length) + ) + + def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection: + # inherits the docstring from interfaces.Dialect.connect + return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501 + + def create_connect_args(self, url: URL) -> ConnectArgsType: + # inherits the docstring from interfaces.Dialect.create_connect_args + opts = url.translate_connect_args() + opts.update(url.query) + return ([], opts) + + def set_engine_execution_options( + self, engine: Engine, opts: Mapping[str, Any] + ) -> None: + supported_names = set(self.connection_characteristics).intersection( + opts + ) + if supported_names: + characteristics: Mapping[str, Any] = util.immutabledict( + (name, opts[name]) for name in supported_names + ) + + @event.listens_for(engine, "engine_connect") + def set_connection_characteristics(connection): + self._set_connection_characteristics( + connection, characteristics + ) + + def set_connection_execution_options( + self, connection: Connection, opts: Mapping[str, Any] + ) -> None: + supported_names = set(self.connection_characteristics).intersection( + opts + ) + if supported_names: + characteristics: Mapping[str, Any] = util.immutabledict( + (name, opts[name]) for name in supported_names + ) + self._set_connection_characteristics(connection, characteristics) + + def _set_connection_characteristics(self, connection, characteristics): + characteristic_values = [ + (name, self.connection_characteristics[name], value) + for name, value in characteristics.items() + ] + + if connection.in_transaction(): + trans_objs = [ + (name, obj) + for name, obj, _ in characteristic_values + if obj.transactional + ] + if trans_objs: + raise exc.InvalidRequestError( + "This connection has already initialized a SQLAlchemy " + "Transaction() object via begin() or autobegin; " + "%s may not be altered unless rollback() or commit() " + "is called first." + % (", ".join(name for name, obj in trans_objs)) + ) + + dbapi_connection = connection.connection.dbapi_connection + for _, characteristic, value in characteristic_values: + characteristic.set_connection_characteristic( + self, connection, dbapi_connection, value + ) + connection.connection._connection_record.finalize_callback.append( + functools.partial(self._reset_characteristics, characteristics) + ) + + def _reset_characteristics(self, characteristics, dbapi_connection): + for characteristic_name in characteristics: + characteristic = self.connection_characteristics[ + characteristic_name + ] + characteristic.reset_characteristic(self, dbapi_connection) + + def do_begin(self, dbapi_connection): + pass + + def do_rollback(self, dbapi_connection): + if self.skip_autocommit_rollback and self.detect_autocommit_setting( + dbapi_connection + ): + return + dbapi_connection.rollback() + + def do_commit(self, dbapi_connection): + dbapi_connection.commit() + + def do_terminate(self, dbapi_connection): + self.do_close(dbapi_connection) + + def do_close(self, dbapi_connection): + dbapi_connection.close() + + @util.memoized_property + def _dialect_specific_select_one(self): + return str(expression.select(1).compile(dialect=self)) + + def _do_ping_w_event(self, dbapi_connection: DBAPIConnection) -> bool: + try: + return self.do_ping(dbapi_connection) + except self.loaded_dbapi.Error as err: + is_disconnect = self.is_disconnect(err, dbapi_connection, None) + + if self._has_events: + try: + Connection._handle_dbapi_exception_noconnection( + err, + self, + is_disconnect=is_disconnect, + invalidate_pool_on_disconnect=False, + is_pre_ping=True, + ) + except exc.StatementError as new_err: + is_disconnect = new_err.connection_invalidated + + if is_disconnect: + return False + else: + raise + + def do_ping(self, dbapi_connection: DBAPIConnection) -> bool: + cursor = dbapi_connection.cursor() + try: + cursor.execute(self._dialect_specific_select_one) + finally: + cursor.close() + return True + + def create_xid(self): + """Create a random two-phase transaction ID. + + This id will be passed to do_begin_twophase(), do_rollback_twophase(), + do_commit_twophase(). Its format is unspecified. + """ + + return "_sa_%032x" % random.randint(0, 2**128) + + def do_savepoint(self, connection, name): + connection.execute(expression.SavepointClause(name)) + + def do_rollback_to_savepoint(self, connection, name): + connection.execute(expression.RollbackToSavepointClause(name)) + + def do_release_savepoint(self, connection, name): + connection.execute(expression.ReleaseSavepointClause(name)) + + def _deliver_insertmanyvalues_batches( + self, + connection, + cursor, + statement, + parameters, + generic_setinputsizes, + context, + ): + context = cast(DefaultExecutionContext, context) + compiled = cast(SQLCompiler, context.compiled) + + _composite_sentinel_proc: Sequence[ + Optional[_ResultProcessorType[Any]] + ] = () + _scalar_sentinel_proc: Optional[_ResultProcessorType[Any]] = None + _sentinel_proc_initialized: bool = False + + compiled_parameters = context.compiled_parameters + + imv = compiled._insertmanyvalues + assert imv is not None + + is_returning: Final[bool] = bool(compiled.effective_returning) + batch_size = context.execution_options.get( + "insertmanyvalues_page_size", self.insertmanyvalues_page_size + ) + + if compiled.schema_translate_map: + schema_translate_map = context.execution_options.get( + "schema_translate_map", {} + ) + else: + schema_translate_map = None + + if is_returning: + result: Optional[List[Any]] = [] + context._insertmanyvalues_rows = result + + sort_by_parameter_order = imv.sort_by_parameter_order + + else: + sort_by_parameter_order = False + result = None + + for imv_batch in compiled._deliver_insertmanyvalues_batches( + statement, + parameters, + compiled_parameters, + generic_setinputsizes, + batch_size, + sort_by_parameter_order, + schema_translate_map, + ): + yield imv_batch + + if is_returning: + + try: + rows = context.fetchall_for_returning(cursor) + except BaseException as be: + connection._handle_dbapi_exception( + be, + sql_util._long_statement(imv_batch.replaced_statement), + imv_batch.replaced_parameters, + None, + context, + is_sub_exec=True, + ) + + # I would have thought "is_returning: Final[bool]" + # would have assured this but pylance thinks not + assert result is not None + + if imv.num_sentinel_columns and not imv_batch.is_downgraded: + composite_sentinel = imv.num_sentinel_columns > 1 + if imv.implicit_sentinel: + # for implicit sentinel, which is currently single-col + # integer autoincrement, do a simple sort. + assert not composite_sentinel + result.extend( + sorted(rows, key=operator.itemgetter(-1)) + ) + continue + + # otherwise, create dictionaries to match up batches + # with parameters + assert imv.sentinel_param_keys + assert imv.sentinel_columns + + _nsc = imv.num_sentinel_columns + + if not _sentinel_proc_initialized: + if composite_sentinel: + _composite_sentinel_proc = [ + col.type._cached_result_processor( + self, cursor_desc[1] + ) + for col, cursor_desc in zip( + imv.sentinel_columns, + cursor.description[-_nsc:], + ) + ] + else: + _scalar_sentinel_proc = ( + imv.sentinel_columns[0] + ).type._cached_result_processor( + self, cursor.description[-1][1] + ) + _sentinel_proc_initialized = True + + rows_by_sentinel: Union[ + Dict[Tuple[Any, ...], Any], + Dict[Any, Any], + ] + if composite_sentinel: + rows_by_sentinel = { + tuple( + (proc(val) if proc else val) + for val, proc in zip( + row[-_nsc:], _composite_sentinel_proc + ) + ): row + for row in rows + } + elif _scalar_sentinel_proc: + rows_by_sentinel = { + _scalar_sentinel_proc(row[-1]): row for row in rows + } + else: + rows_by_sentinel = {row[-1]: row for row in rows} + + if len(rows_by_sentinel) != len(imv_batch.batch): + # see test_insert_exec.py:: + # IMVSentinelTest::test_sentinel_incorrect_rowcount + # for coverage / demonstration + raise exc.InvalidRequestError( + f"Sentinel-keyed result set did not produce " + f"correct number of rows {len(imv_batch.batch)}; " + "produced " + f"{len(rows_by_sentinel)}. Please ensure the " + "sentinel column is fully unique and populated in " + "all cases." + ) + + try: + ordered_rows = [ + rows_by_sentinel[sentinel_keys] + for sentinel_keys in imv_batch.sentinel_values + ] + except KeyError as ke: + # see test_insert_exec.py:: + # IMVSentinelTest::test_sentinel_cant_match_keys + # for coverage / demonstration + raise exc.InvalidRequestError( + f"Can't match sentinel values in result set to " + f"parameter sets; key {ke.args[0]!r} was not " + "found. " + "There may be a mismatch between the datatype " + "passed to the DBAPI driver vs. that which it " + "returns in a result row. Ensure the given " + "Python value matches the expected result type " + "*exactly*, taking care to not rely upon implicit " + "conversions which may occur such as when using " + "strings in place of UUID or integer values, etc. " + ) from ke + + result.extend(ordered_rows) + + else: + result.extend(rows) + + def do_executemany(self, cursor, statement, parameters, context=None): + cursor.executemany(statement, parameters) + + def do_execute(self, cursor, statement, parameters, context=None): + cursor.execute(statement, parameters) + + def do_execute_no_params(self, cursor, statement, context=None): + cursor.execute(statement) + + def is_disconnect( + self, + e: DBAPIModule.Error, + connection: Union[ + pool.PoolProxiedConnection, interfaces.DBAPIConnection, None + ], + cursor: Optional[interfaces.DBAPICursor], + ) -> bool: + return False + + @util.memoized_instancemethod + def _gen_allowed_isolation_levels(self, dbapi_conn): + try: + raw_levels = list(self.get_isolation_level_values(dbapi_conn)) + except NotImplementedError: + return None + else: + normalized_levels = [ + level.replace("_", " ").upper() for level in raw_levels + ] + if raw_levels != normalized_levels: + raise ValueError( + f"Dialect {self.name!r} get_isolation_level_values() " + f"method should return names as UPPERCASE using spaces, " + f"not underscores; got " + f"{sorted(set(raw_levels).difference(normalized_levels))}" + ) + return tuple(normalized_levels) + + def _assert_and_set_isolation_level(self, dbapi_conn, level): + level = level.replace("_", " ").upper() + + _allowed_isolation_levels = self._gen_allowed_isolation_levels( + dbapi_conn + ) + if ( + _allowed_isolation_levels + and level not in _allowed_isolation_levels + ): + raise exc.ArgumentError( + f"Invalid value {level!r} for isolation_level. " + f"Valid isolation levels for {self.name!r} are " + f"{', '.join(_allowed_isolation_levels)}" + ) + + self.set_isolation_level(dbapi_conn, level) + + def reset_isolation_level(self, dbapi_conn): + if self._on_connect_isolation_level is not None: + assert ( + self._on_connect_isolation_level == "AUTOCOMMIT" + or self._on_connect_isolation_level + == self.default_isolation_level + ) + self._assert_and_set_isolation_level( + dbapi_conn, self._on_connect_isolation_level + ) + else: + assert self.default_isolation_level is not None + self._assert_and_set_isolation_level( + dbapi_conn, + self.default_isolation_level, + ) + + def normalize_name(self, name): + if name is None: + return None + + name_lower = name.lower() + name_upper = name.upper() + + if name_upper == name_lower: + # name has no upper/lower conversion, e.g. non-european characters. + # return unchanged + return name + elif name_upper == name and not ( + self.identifier_preparer._requires_quotes + )(name_lower): + # name is all uppercase and doesn't require quoting; normalize + # to all lower case + return name_lower + elif name_lower == name: + # name is all lower case, which if denormalized means we need to + # force quoting on it + return quoted_name(name, quote=True) + else: + # name is mixed case, means it will be quoted in SQL when used + # later, no normalizes + return name + + def denormalize_name(self, name): + if name is None: + return None + + name_lower = name.lower() + name_upper = name.upper() + + if name_upper == name_lower: + # name has no upper/lower conversion, e.g. non-european characters. + # return unchanged + return name + elif name_lower == name and not ( + self.identifier_preparer._requires_quotes + )(name_lower): + name = name_upper + return name + + def get_driver_connection(self, connection: DBAPIConnection) -> Any: + return connection + + def _overrides_default(self, method): + return ( + getattr(type(self), method).__code__ + is not getattr(DefaultDialect, method).__code__ + ) + + def _default_multi_reflect( + self, + single_tbl_method, + connection, + kind, + schema, + filter_names, + scope, + **kw, + ): + names_fns = [] + temp_names_fns = [] + if ObjectKind.TABLE in kind: + names_fns.append(self.get_table_names) + temp_names_fns.append(self.get_temp_table_names) + if ObjectKind.VIEW in kind: + names_fns.append(self.get_view_names) + temp_names_fns.append(self.get_temp_view_names) + if ObjectKind.MATERIALIZED_VIEW in kind: + names_fns.append(self.get_materialized_view_names) + # no temp materialized view at the moment + # temp_names_fns.append(self.get_temp_materialized_view_names) + + unreflectable = kw.pop("unreflectable", {}) + + if ( + filter_names + and scope is ObjectScope.ANY + and kind is ObjectKind.ANY + ): + # if names are given and no qualification on type of table + # (i.e. the Table(..., autoload) case), take the names as given, + # don't run names queries. If a table does not exit + # NoSuchTableError is raised and it's skipped + + # this also suits the case for mssql where we can reflect + # individual temp tables but there's no temp_names_fn + names = filter_names + else: + names = [] + name_kw = {"schema": schema, **kw} + fns = [] + if ObjectScope.DEFAULT in scope: + fns.extend(names_fns) + if ObjectScope.TEMPORARY in scope: + fns.extend(temp_names_fns) + + for fn in fns: + try: + names.extend(fn(connection, **name_kw)) + except NotImplementedError: + pass + + if filter_names: + filter_names = set(filter_names) + + # iterate over all the tables/views and call the single table method + for table in names: + if not filter_names or table in filter_names: + key = (schema, table) + try: + yield ( + key, + single_tbl_method( + connection, table, schema=schema, **kw + ), + ) + except exc.UnreflectableTableError as err: + if key not in unreflectable: + unreflectable[key] = err + except exc.NoSuchTableError: + pass + + def get_multi_table_options(self, connection, **kw): + return self._default_multi_reflect( + self.get_table_options, connection, **kw + ) + + def get_multi_columns(self, connection, **kw): + return self._default_multi_reflect(self.get_columns, connection, **kw) + + def get_multi_pk_constraint(self, connection, **kw): + return self._default_multi_reflect( + self.get_pk_constraint, connection, **kw + ) + + def get_multi_foreign_keys(self, connection, **kw): + return self._default_multi_reflect( + self.get_foreign_keys, connection, **kw + ) + + def get_multi_indexes(self, connection, **kw): + return self._default_multi_reflect(self.get_indexes, connection, **kw) + + def get_multi_unique_constraints(self, connection, **kw): + return self._default_multi_reflect( + self.get_unique_constraints, connection, **kw + ) + + def get_multi_check_constraints(self, connection, **kw): + return self._default_multi_reflect( + self.get_check_constraints, connection, **kw + ) + + def get_multi_table_comment(self, connection, **kw): + return self._default_multi_reflect( + self.get_table_comment, connection, **kw + ) + + +class StrCompileDialect(DefaultDialect): + statement_compiler = compiler.StrSQLCompiler + ddl_compiler = compiler.DDLCompiler + type_compiler_cls = compiler.StrSQLTypeCompiler + preparer = compiler.IdentifierPreparer + + insert_returning = True + update_returning = True + delete_returning = True + + supports_statement_cache = True + + supports_identity_columns = True + + supports_sequences = True + sequences_optional = True + preexecute_autoincrement_sequences = False + + supports_native_boolean = True + + supports_multivalues_insert = True + supports_simple_order_by_label = True + + +class DefaultExecutionContext(ExecutionContext): + isinsert = False + isupdate = False + isdelete = False + is_crud = False + is_text = False + isddl = False + + execute_style: ExecuteStyle = ExecuteStyle.EXECUTE + + compiled: Optional[Compiled] = None + result_column_struct: Optional[ + Tuple[List[ResultColumnsEntry], bool, bool, bool, bool] + ] = None + returned_default_rows: Optional[Sequence[Row[Any]]] = None + + execution_options: _ExecuteOptions = util.EMPTY_DICT + + cursor_fetch_strategy = _cursor._DEFAULT_FETCH + + invoked_statement: Optional[Executable] = None + + _is_implicit_returning = False + _is_explicit_returning = False + _is_supplemental_returning = False + _is_server_side = False + + _soft_closed = False + + _rowcount: Optional[int] = None + + # a hook for SQLite's translation of + # result column names + # NOTE: pyhive is using this hook, can't remove it :( + _translate_colname: Optional[ + Callable[[str], Tuple[str, Optional[str]]] + ] = None + + _expanded_parameters: Mapping[str, List[str]] = util.immutabledict() + """used by set_input_sizes(). + + This collection comes from ``ExpandedState.parameter_expansion``. + + """ + + cache_hit = NO_CACHE_KEY + + root_connection: Connection + _dbapi_connection: PoolProxiedConnection + dialect: Dialect + unicode_statement: str + cursor: DBAPICursor + compiled_parameters: List[_MutableCoreSingleExecuteParams] + parameters: _DBAPIMultiExecuteParams + extracted_parameters: Optional[Sequence[BindParameter[Any]]] + + _empty_dict_params = cast("Mapping[str, Any]", util.EMPTY_DICT) + + _insertmanyvalues_rows: Optional[List[Tuple[Any, ...]]] = None + _num_sentinel_cols: int = 0 + + @classmethod + def _init_ddl( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + compiled_ddl: DDLCompiler, + ) -> ExecutionContext: + """Initialize execution context for an ExecutableDDLElement + construct.""" + + self = cls.__new__(cls) + self.root_connection = connection + self._dbapi_connection = dbapi_connection + self.dialect = connection.dialect + + self.compiled = compiled = compiled_ddl + self.isddl = True + + self.execution_options = execution_options + + self.unicode_statement = str(compiled) + if compiled.schema_translate_map: + schema_translate_map = self.execution_options.get( + "schema_translate_map", {} + ) + + rst = compiled.preparer._render_schema_translates + self.unicode_statement = rst( + self.unicode_statement, schema_translate_map + ) + + self.statement = self.unicode_statement + + self.cursor = self.create_cursor() + self.compiled_parameters = [] + + if dialect.positional: + self.parameters = [dialect.execute_sequence_format()] + else: + self.parameters = [self._empty_dict_params] + + return self + + @classmethod + def _init_compiled( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + compiled: SQLCompiler, + parameters: _CoreMultiExecuteParams, + invoked_statement: Executable, + extracted_parameters: Optional[Sequence[BindParameter[Any]]], + cache_hit: CacheStats = CacheStats.CACHING_DISABLED, + ) -> ExecutionContext: + """Initialize execution context for a Compiled construct.""" + + self = cls.__new__(cls) + self.root_connection = connection + self._dbapi_connection = dbapi_connection + self.dialect = connection.dialect + self.extracted_parameters = extracted_parameters + self.invoked_statement = invoked_statement + self.compiled = compiled + self.cache_hit = cache_hit + + self.execution_options = execution_options + + self.result_column_struct = ( + compiled._result_columns, + compiled._ordered_columns, + compiled._textual_ordered_columns, + compiled._ad_hoc_textual, + compiled._loose_column_name_matching, + ) + + self.isinsert = ii = compiled.isinsert + self.isupdate = iu = compiled.isupdate + self.isdelete = id_ = compiled.isdelete + self.is_text = compiled.isplaintext + + if ii or iu or id_: + dml_statement = compiled.compile_state.statement # type: ignore + if TYPE_CHECKING: + assert isinstance(dml_statement, UpdateBase) + self.is_crud = True + self._is_explicit_returning = ier = bool(dml_statement._returning) + self._is_implicit_returning = iir = bool( + compiled.implicit_returning + ) + if iir and dml_statement._supplemental_returning: + self._is_supplemental_returning = True + + # dont mix implicit and explicit returning + assert not (iir and ier) + + if (ier or iir) and compiled.for_executemany: + if ii and not self.dialect.insert_executemany_returning: + raise exc.InvalidRequestError( + f"Dialect {self.dialect.dialect_description} with " + f"current server capabilities does not support " + "INSERT..RETURNING when executemany is used" + ) + elif ( + ii + and dml_statement._sort_by_parameter_order + and not self.dialect.insert_executemany_returning_sort_by_parameter_order # noqa: E501 + ): + raise exc.InvalidRequestError( + f"Dialect {self.dialect.dialect_description} with " + f"current server capabilities does not support " + "INSERT..RETURNING with deterministic row ordering " + "when executemany is used" + ) + elif ( + ii + and self.dialect.use_insertmanyvalues + and not compiled._insertmanyvalues + ): + raise exc.InvalidRequestError( + 'Statement does not have "insertmanyvalues" ' + "enabled, can't use INSERT..RETURNING with " + "executemany in this case." + ) + elif iu and not self.dialect.update_executemany_returning: + raise exc.InvalidRequestError( + f"Dialect {self.dialect.dialect_description} with " + f"current server capabilities does not support " + "UPDATE..RETURNING when executemany is used" + ) + elif id_ and not self.dialect.delete_executemany_returning: + raise exc.InvalidRequestError( + f"Dialect {self.dialect.dialect_description} with " + f"current server capabilities does not support " + "DELETE..RETURNING when executemany is used" + ) + + if not parameters: + self.compiled_parameters = [ + compiled.construct_params( + extracted_parameters=extracted_parameters, + escape_names=False, + ) + ] + else: + self.compiled_parameters = [ + compiled.construct_params( + m, + escape_names=False, + _group_number=grp, + extracted_parameters=extracted_parameters, + ) + for grp, m in enumerate(parameters) + ] + + if len(parameters) > 1: + if self.isinsert and compiled._insertmanyvalues: + self.execute_style = ExecuteStyle.INSERTMANYVALUES + + imv = compiled._insertmanyvalues + if imv.sentinel_columns is not None: + self._num_sentinel_cols = imv.num_sentinel_columns + else: + self.execute_style = ExecuteStyle.EXECUTEMANY + + self.unicode_statement = compiled.string + + self.cursor = self.create_cursor() + + if self.compiled.insert_prefetch or self.compiled.update_prefetch: + self._process_execute_defaults() + + processors = compiled._bind_processors + + flattened_processors: Mapping[ + str, _BindProcessorType[Any] + ] = processors # type: ignore[assignment] + + if compiled.literal_execute_params or compiled.post_compile_params: + if self.executemany: + raise exc.InvalidRequestError( + "'literal_execute' or 'expanding' parameters can't be " + "used with executemany()" + ) + + expanded_state = compiled._process_parameters_for_postcompile( + self.compiled_parameters[0] + ) + + # re-assign self.unicode_statement + self.unicode_statement = expanded_state.statement + + self._expanded_parameters = expanded_state.parameter_expansion + + flattened_processors = dict(processors) # type: ignore + flattened_processors.update(expanded_state.processors) + positiontup = expanded_state.positiontup + elif compiled.positional: + positiontup = self.compiled.positiontup + else: + positiontup = None + + if compiled.schema_translate_map: + schema_translate_map = self.execution_options.get( + "schema_translate_map", {} + ) + rst = compiled.preparer._render_schema_translates + self.unicode_statement = rst( + self.unicode_statement, schema_translate_map + ) + + # final self.unicode_statement is now assigned, encode if needed + # by dialect + self.statement = self.unicode_statement + + # Convert the dictionary of bind parameter values + # into a dict or list to be sent to the DBAPI's + # execute() or executemany() method. + + if compiled.positional: + core_positional_parameters: MutableSequence[Sequence[Any]] = [] + assert positiontup is not None + for compiled_params in self.compiled_parameters: + l_param: List[Any] = [ + ( + flattened_processors[key](compiled_params[key]) + if key in flattened_processors + else compiled_params[key] + ) + for key in positiontup + ] + core_positional_parameters.append( + dialect.execute_sequence_format(l_param) + ) + + self.parameters = core_positional_parameters + else: + core_dict_parameters: MutableSequence[Dict[str, Any]] = [] + escaped_names = compiled.escaped_bind_names + + # note that currently, "expanded" parameters will be present + # in self.compiled_parameters in their quoted form. This is + # slightly inconsistent with the approach taken as of + # #8056 where self.compiled_parameters is meant to contain unquoted + # param names. + d_param: Dict[str, Any] + for compiled_params in self.compiled_parameters: + if escaped_names: + d_param = { + escaped_names.get(key, key): ( + flattened_processors[key](compiled_params[key]) + if key in flattened_processors + else compiled_params[key] + ) + for key in compiled_params + } + else: + d_param = { + key: ( + flattened_processors[key](compiled_params[key]) + if key in flattened_processors + else compiled_params[key] + ) + for key in compiled_params + } + + core_dict_parameters.append(d_param) + + self.parameters = core_dict_parameters + + return self + + @classmethod + def _init_statement( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + statement: str, + parameters: _DBAPIMultiExecuteParams, + ) -> ExecutionContext: + """Initialize execution context for a string SQL statement.""" + + self = cls.__new__(cls) + self.root_connection = connection + self._dbapi_connection = dbapi_connection + self.dialect = connection.dialect + self.is_text = True + + self.execution_options = execution_options + + if not parameters: + if self.dialect.positional: + self.parameters = [dialect.execute_sequence_format()] + else: + self.parameters = [self._empty_dict_params] + elif isinstance(parameters[0], dialect.execute_sequence_format): + self.parameters = parameters + elif isinstance(parameters[0], dict): + self.parameters = parameters + else: + self.parameters = [ + dialect.execute_sequence_format(p) for p in parameters + ] + + if len(parameters) > 1: + self.execute_style = ExecuteStyle.EXECUTEMANY + + self.statement = self.unicode_statement = statement + + self.cursor = self.create_cursor() + return self + + @classmethod + def _init_default( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + ) -> ExecutionContext: + """Initialize execution context for a ColumnDefault construct.""" + + self = cls.__new__(cls) + self.root_connection = connection + self._dbapi_connection = dbapi_connection + self.dialect = connection.dialect + + self.execution_options = execution_options + + self.cursor = self.create_cursor() + return self + + def _get_cache_stats(self) -> str: + if self.compiled is None: + return "raw sql" + + now = perf_counter() + + ch = self.cache_hit + + gen_time = self.compiled._gen_time + assert gen_time is not None + + if ch is NO_CACHE_KEY: + return "no key %.5fs" % (now - gen_time,) + elif ch is CACHE_HIT: + return "cached since %.4gs ago" % (now - gen_time,) + elif ch is CACHE_MISS: + return "generated in %.5fs" % (now - gen_time,) + elif ch is CACHING_DISABLED: + if "_cache_disable_reason" in self.execution_options: + return "caching disabled (%s) %.5fs " % ( + self.execution_options["_cache_disable_reason"], + now - gen_time, + ) + else: + return "caching disabled %.5fs" % (now - gen_time,) + elif ch is NO_DIALECT_SUPPORT: + return "dialect %s+%s does not support caching %.5fs" % ( + self.dialect.name, + self.dialect.driver, + now - gen_time, + ) + else: + return "unknown" + + @property + def executemany(self): # type: ignore[override] + return self.execute_style in ( + ExecuteStyle.EXECUTEMANY, + ExecuteStyle.INSERTMANYVALUES, + ) + + @util.memoized_property + def identifier_preparer(self): + if self.compiled: + return self.compiled.preparer + elif "schema_translate_map" in self.execution_options: + return self.dialect.identifier_preparer._with_schema_translate( + self.execution_options["schema_translate_map"] + ) + else: + return self.dialect.identifier_preparer + + @util.memoized_property + def engine(self): + return self.root_connection.engine + + @util.memoized_property + def postfetch_cols(self) -> Optional[Sequence[Column[Any]]]: + if TYPE_CHECKING: + assert isinstance(self.compiled, SQLCompiler) + return self.compiled.postfetch + + @util.memoized_property + def prefetch_cols(self) -> Optional[Sequence[Column[Any]]]: + if TYPE_CHECKING: + assert isinstance(self.compiled, SQLCompiler) + if self.isinsert: + return self.compiled.insert_prefetch + elif self.isupdate: + return self.compiled.update_prefetch + else: + return () + + @util.memoized_property + def no_parameters(self): + return self.execution_options.get("no_parameters", False) + + def _execute_scalar( + self, + stmt: str, + type_: Optional[TypeEngine[Any]], + parameters: Optional[_DBAPISingleExecuteParams] = None, + ) -> Any: + """Execute a string statement on the current cursor, returning a + scalar result. + + Used to fire off sequences, default phrases, and "select lastrowid" + types of statements individually or in the context of a parent INSERT + or UPDATE statement. + + """ + + conn = self.root_connection + + if "schema_translate_map" in self.execution_options: + schema_translate_map = self.execution_options.get( + "schema_translate_map", {} + ) + + rst = self.identifier_preparer._render_schema_translates + stmt = rst(stmt, schema_translate_map) + + if not parameters: + if self.dialect.positional: + parameters = self.dialect.execute_sequence_format() + else: + parameters = {} + + conn._cursor_execute(self.cursor, stmt, parameters, context=self) + row = self.cursor.fetchone() + if row is not None: + r = row[0] + else: + r = None + if type_ is not None: + # apply type post processors to the result + proc = type_._cached_result_processor( + self.dialect, self.cursor.description[0][1] + ) + if proc: + return proc(r) + return r + + @util.memoized_property + def connection(self): + return self.root_connection + + def _use_server_side_cursor(self): + if not self.dialect.supports_server_side_cursors: + return False + + if self.dialect.server_side_cursors: + # this is deprecated + use_server_side = self.execution_options.get( + "stream_results", True + ) and ( + self.compiled + and isinstance(self.compiled.statement, expression.Selectable) + or ( + ( + not self.compiled + or isinstance( + self.compiled.statement, expression.TextClause + ) + ) + and self.unicode_statement + and SERVER_SIDE_CURSOR_RE.match(self.unicode_statement) + ) + ) + else: + use_server_side = self.execution_options.get( + "stream_results", False + ) + + return use_server_side + + def create_cursor(self) -> DBAPICursor: + if ( + # inlining initial preference checks for SS cursors + self.dialect.supports_server_side_cursors + and ( + self.execution_options.get("stream_results", False) + or ( + self.dialect.server_side_cursors + and self._use_server_side_cursor() + ) + ) + ): + self._is_server_side = True + return self.create_server_side_cursor() + else: + self._is_server_side = False + return self.create_default_cursor() + + def fetchall_for_returning(self, cursor): + return cursor.fetchall() + + def create_default_cursor(self) -> DBAPICursor: + return self._dbapi_connection.cursor() + + def create_server_side_cursor(self) -> DBAPICursor: + raise NotImplementedError() + + def pre_exec(self): + pass + + def get_out_parameter_values(self, names): + raise NotImplementedError( + "This dialect does not support OUT parameters" + ) + + def post_exec(self): + pass + + def get_result_processor( + self, type_: TypeEngine[Any], colname: str, coltype: DBAPIType + ) -> Optional[_ResultProcessorType[Any]]: + """Return a 'result processor' for a given type as present in + cursor.description. + + This has a default implementation that dialects can override + for context-sensitive result type handling. + + """ + return type_._cached_result_processor(self.dialect, coltype) + + def get_lastrowid(self) -> int: + """return self.cursor.lastrowid, or equivalent, after an INSERT. + + This may involve calling special cursor functions, issuing a new SELECT + on the cursor (or a new one), or returning a stored value that was + calculated within post_exec(). + + This function will only be called for dialects which support "implicit" + primary key generation, keep preexecute_autoincrement_sequences set to + False, and when no explicit id value was bound to the statement. + + The function is called once for an INSERT statement that would need to + return the last inserted primary key for those dialects that make use + of the lastrowid concept. In these cases, it is called directly after + :meth:`.ExecutionContext.post_exec`. + + """ + return self.cursor.lastrowid + + def handle_dbapi_exception(self, e): + pass + + @util.non_memoized_property + def rowcount(self) -> int: + if self._rowcount is not None: + return self._rowcount + else: + return self.cursor.rowcount + + @property + def _has_rowcount(self): + return self._rowcount is not None + + def supports_sane_rowcount(self): + return self.dialect.supports_sane_rowcount + + def supports_sane_multi_rowcount(self): + return self.dialect.supports_sane_multi_rowcount + + def _setup_result_proxy(self): + exec_opt = self.execution_options + + if self._rowcount is None and exec_opt.get("preserve_rowcount", False): + self._rowcount = self.cursor.rowcount + + yp: Optional[Union[int, bool]] + if self.is_crud or self.is_text: + result = self._setup_dml_or_text_result() + yp = False + else: + yp = exec_opt.get("yield_per", None) + sr = self._is_server_side or exec_opt.get("stream_results", False) + strategy = self.cursor_fetch_strategy + if sr and strategy is _cursor._DEFAULT_FETCH: + strategy = _cursor.BufferedRowCursorFetchStrategy( + self.cursor, self.execution_options + ) + cursor_description: _DBAPICursorDescription = ( + strategy.alternate_cursor_description + or self.cursor.description + ) + if cursor_description is None: + strategy = _cursor._NO_CURSOR_DQL + + result = _cursor.CursorResult(self, strategy, cursor_description) + + compiled = self.compiled + + if ( + compiled + and not self.isddl + and cast(SQLCompiler, compiled).has_out_parameters + ): + self._setup_out_parameters(result) + + self._soft_closed = result._soft_closed + + if yp: + result = result.yield_per(yp) + + return result + + def _setup_out_parameters(self, result): + compiled = cast(SQLCompiler, self.compiled) + + out_bindparams = [ + (param, name) + for param, name in compiled.bind_names.items() + if param.isoutparam + ] + out_parameters = {} + + for bindparam, raw_value in zip( + [param for param, name in out_bindparams], + self.get_out_parameter_values( + [name for param, name in out_bindparams] + ), + ): + type_ = bindparam.type + impl_type = type_.dialect_impl(self.dialect) + dbapi_type = impl_type.get_dbapi_type(self.dialect.loaded_dbapi) + result_processor = impl_type.result_processor( + self.dialect, dbapi_type + ) + if result_processor is not None: + raw_value = result_processor(raw_value) + out_parameters[bindparam.key] = raw_value + + result.out_parameters = out_parameters + + def _setup_dml_or_text_result(self): + compiled = cast(SQLCompiler, self.compiled) + + strategy: ResultFetchStrategy = self.cursor_fetch_strategy + + if self.isinsert: + if ( + self.execute_style is ExecuteStyle.INSERTMANYVALUES + and compiled.effective_returning + ): + strategy = _cursor.FullyBufferedCursorFetchStrategy( + self.cursor, + initial_buffer=self._insertmanyvalues_rows, + # maintain alt cursor description if set by the + # dialect, e.g. mssql preserves it + alternate_description=( + strategy.alternate_cursor_description + ), + ) + + if compiled.postfetch_lastrowid: + self.inserted_primary_key_rows = ( + self._setup_ins_pk_from_lastrowid() + ) + # else if not self._is_implicit_returning, + # the default inserted_primary_key_rows accessor will + # return an "empty" primary key collection when accessed. + + if self._is_server_side and strategy is _cursor._DEFAULT_FETCH: + strategy = _cursor.BufferedRowCursorFetchStrategy( + self.cursor, self.execution_options + ) + + if strategy is _cursor._NO_CURSOR_DML: + cursor_description = None + else: + cursor_description = ( + strategy.alternate_cursor_description + or self.cursor.description + ) + + if cursor_description is None: + strategy = _cursor._NO_CURSOR_DML + elif self._num_sentinel_cols: + assert self.execute_style is ExecuteStyle.INSERTMANYVALUES + # strip out the sentinel columns from cursor description + # a similar logic is done to the rows only in CursorResult + cursor_description = cursor_description[ + 0 : -self._num_sentinel_cols + ] + + result: _cursor.CursorResult[Any] = _cursor.CursorResult( + self, strategy, cursor_description + ) + + if self.isinsert: + if self._is_implicit_returning: + rows = result.all() + + self.returned_default_rows = rows + + self.inserted_primary_key_rows = ( + self._setup_ins_pk_from_implicit_returning(result, rows) + ) + + # test that it has a cursor metadata that is accurate. the + # first row will have been fetched and current assumptions + # are that the result has only one row, until executemany() + # support is added here. + assert result._metadata.returns_rows + + # Insert statement has both return_defaults() and + # returning(). rewind the result on the list of rows + # we just used. + if self._is_supplemental_returning: + result._rewind(rows) + else: + result._soft_close() + elif not self._is_explicit_returning: + result._soft_close() + + # we assume here the result does not return any rows. + # *usually*, this will be true. However, some dialects + # such as that of MSSQL/pyodbc need to SELECT a post fetch + # function so this is not necessarily true. + # assert not result.returns_rows + + elif self._is_implicit_returning: + rows = result.all() + + if rows: + self.returned_default_rows = rows + self._rowcount = len(rows) + + if self._is_supplemental_returning: + result._rewind(rows) + else: + result._soft_close() + + # test that it has a cursor metadata that is accurate. + # the rows have all been fetched however. + assert result._metadata.returns_rows + + elif not result._metadata.returns_rows: + # no results, get rowcount + # (which requires open cursor on some drivers) + if self._rowcount is None: + self._rowcount = self.cursor.rowcount + result._soft_close() + elif self.isupdate or self.isdelete: + if self._rowcount is None: + self._rowcount = self.cursor.rowcount + return result + + @util.memoized_property + def inserted_primary_key_rows(self): + # if no specific "get primary key" strategy was set up + # during execution, return a "default" primary key based + # on what's in the compiled_parameters and nothing else. + return self._setup_ins_pk_from_empty() + + def _setup_ins_pk_from_lastrowid(self): + getter = cast( + SQLCompiler, self.compiled + )._inserted_primary_key_from_lastrowid_getter + lastrowid = self.get_lastrowid() + return [getter(lastrowid, self.compiled_parameters[0])] + + def _setup_ins_pk_from_empty(self): + getter = cast( + SQLCompiler, self.compiled + )._inserted_primary_key_from_lastrowid_getter + return [getter(None, param) for param in self.compiled_parameters] + + def _setup_ins_pk_from_implicit_returning(self, result, rows): + if not rows: + return [] + + getter = cast( + SQLCompiler, self.compiled + )._inserted_primary_key_from_returning_getter + compiled_params = self.compiled_parameters + + return [ + getter(row, param) for row, param in zip(rows, compiled_params) + ] + + def lastrow_has_defaults(self) -> bool: + return (self.isinsert or self.isupdate) and bool( + cast(SQLCompiler, self.compiled).postfetch + ) + + def _prepare_set_input_sizes( + self, + ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]: + """Given a cursor and ClauseParameters, prepare arguments + in order to call the appropriate + style of ``setinputsizes()`` on the cursor, using DB-API types + from the bind parameter's ``TypeEngine`` objects. + + This method only called by those dialects which set the + :attr:`.Dialect.bind_typing` attribute to + :attr:`.BindTyping.SETINPUTSIZES`. Python-oracledb and cx_Oracle are + the only DBAPIs that requires setinputsizes(); pyodbc offers it as an + option. + + Prior to SQLAlchemy 2.0, the setinputsizes() approach was also used + for pg8000 and asyncpg, which has been changed to inline rendering + of casts. + + """ + if self.isddl or self.is_text: + return None + + compiled = cast(SQLCompiler, self.compiled) + + inputsizes = compiled._get_set_input_sizes_lookup() + + if inputsizes is None: + return None + + dialect = self.dialect + + # all of the rest of this... cython? + + if dialect._has_events: + inputsizes = dict(inputsizes) + dialect.dispatch.do_setinputsizes( + inputsizes, self.cursor, self.statement, self.parameters, self + ) + + if compiled.escaped_bind_names: + escaped_bind_names = compiled.escaped_bind_names + else: + escaped_bind_names = None + + if dialect.positional: + items = [ + (key, compiled.binds[key]) + for key in compiled.positiontup or () + ] + else: + items = [ + (key, bindparam) + for bindparam, key in compiled.bind_names.items() + ] + + generic_inputsizes: List[Tuple[str, Any, TypeEngine[Any]]] = [] + for key, bindparam in items: + if bindparam in compiled.literal_execute_params: + continue + + if key in self._expanded_parameters: + if is_tuple_type(bindparam.type): + num = len(bindparam.type.types) + dbtypes = inputsizes[bindparam] + generic_inputsizes.extend( + ( + ( + escaped_bind_names.get(paramname, paramname) + if escaped_bind_names is not None + else paramname + ), + dbtypes[idx % num], + bindparam.type.types[idx % num], + ) + for idx, paramname in enumerate( + self._expanded_parameters[key] + ) + ) + else: + dbtype = inputsizes.get(bindparam, None) + generic_inputsizes.extend( + ( + ( + escaped_bind_names.get(paramname, paramname) + if escaped_bind_names is not None + else paramname + ), + dbtype, + bindparam.type, + ) + for paramname in self._expanded_parameters[key] + ) + else: + dbtype = inputsizes.get(bindparam, None) + + escaped_name = ( + escaped_bind_names.get(key, key) + if escaped_bind_names is not None + else key + ) + + generic_inputsizes.append( + (escaped_name, dbtype, bindparam.type) + ) + + return generic_inputsizes + + def _exec_default(self, column, default, type_): + if default.is_sequence: + return self.fire_sequence(default, type_) + elif default.is_callable: + # this codepath is not normally used as it's inlined + # into _process_execute_defaults + self.current_column = column + return default.arg(self) + elif default.is_clause_element: + return self._exec_default_clause_element(column, default, type_) + else: + # this codepath is not normally used as it's inlined + # into _process_execute_defaults + return default.arg + + def _exec_default_clause_element(self, column, default, type_): + # execute a default that's a complete clause element. Here, we have + # to re-implement a miniature version of the compile->parameters-> + # cursor.execute() sequence, since we don't want to modify the state + # of the connection / result in progress or create new connection/ + # result objects etc. + # .. versionchanged:: 1.4 + + if not default._arg_is_typed: + default_arg = expression.type_coerce(default.arg, type_) + else: + default_arg = default.arg + compiled = expression.select(default_arg).compile(dialect=self.dialect) + compiled_params = compiled.construct_params() + processors = compiled._bind_processors + if compiled.positional: + parameters = self.dialect.execute_sequence_format( + [ + ( + processors[key](compiled_params[key]) # type: ignore + if key in processors + else compiled_params[key] + ) + for key in compiled.positiontup or () + ] + ) + else: + parameters = { + key: ( + processors[key](compiled_params[key]) # type: ignore + if key in processors + else compiled_params[key] + ) + for key in compiled_params + } + return self._execute_scalar( + str(compiled), type_, parameters=parameters + ) + + current_parameters: Optional[_CoreSingleExecuteParams] = None + """A dictionary of parameters applied to the current row. + + This attribute is only available in the context of a user-defined default + generation function, e.g. as described at :ref:`context_default_functions`. + It consists of a dictionary which includes entries for each column/value + pair that is to be part of the INSERT or UPDATE statement. The keys of the + dictionary will be the key value of each :class:`_schema.Column`, + which is usually + synonymous with the name. + + Note that the :attr:`.DefaultExecutionContext.current_parameters` attribute + does not accommodate for the "multi-values" feature of the + :meth:`_expression.Insert.values` method. The + :meth:`.DefaultExecutionContext.get_current_parameters` method should be + preferred. + + .. seealso:: + + :meth:`.DefaultExecutionContext.get_current_parameters` + + :ref:`context_default_functions` + + """ + + def get_current_parameters(self, isolate_multiinsert_groups=True): + """Return a dictionary of parameters applied to the current row. + + This method can only be used in the context of a user-defined default + generation function, e.g. as described at + :ref:`context_default_functions`. When invoked, a dictionary is + returned which includes entries for each column/value pair that is part + of the INSERT or UPDATE statement. The keys of the dictionary will be + the key value of each :class:`_schema.Column`, + which is usually synonymous + with the name. + + :param isolate_multiinsert_groups=True: indicates that multi-valued + INSERT constructs created using :meth:`_expression.Insert.values` + should be + handled by returning only the subset of parameters that are local + to the current column default invocation. When ``False``, the + raw parameters of the statement are returned including the + naming convention used in the case of multi-valued INSERT. + + .. versionadded:: 1.2 added + :meth:`.DefaultExecutionContext.get_current_parameters` + which provides more functionality over the existing + :attr:`.DefaultExecutionContext.current_parameters` + attribute. + + .. seealso:: + + :attr:`.DefaultExecutionContext.current_parameters` + + :ref:`context_default_functions` + + """ + try: + parameters = self.current_parameters + column = self.current_column + except AttributeError: + raise exc.InvalidRequestError( + "get_current_parameters() can only be invoked in the " + "context of a Python side column default function" + ) + else: + assert column is not None + assert parameters is not None + compile_state = cast( + "DMLState", cast(SQLCompiler, self.compiled).compile_state + ) + assert compile_state is not None + if ( + isolate_multiinsert_groups + and dml.isinsert(compile_state) + and compile_state._has_multi_parameters + ): + if column._is_multiparam_column: + index = column.index + 1 + d = {column.original.key: parameters[column.key]} + else: + d = {column.key: parameters[column.key]} + index = 0 + assert compile_state._dict_parameters is not None + keys = compile_state._dict_parameters.keys() + d.update( + (key, parameters["%s_m%d" % (key, index)]) for key in keys + ) + return d + else: + return parameters + + def get_insert_default(self, column): + if column.default is None: + return None + else: + return self._exec_default(column, column.default, column.type) + + def get_update_default(self, column): + if column.onupdate is None: + return None + else: + return self._exec_default(column, column.onupdate, column.type) + + def _process_execute_defaults(self): + compiled = cast(SQLCompiler, self.compiled) + + key_getter = compiled._within_exec_param_key_getter + + sentinel_counter = 0 + + if compiled.insert_prefetch: + prefetch_recs = [ + ( + c, + key_getter(c), + c._default_description_tuple, + self.get_insert_default, + ) + for c in compiled.insert_prefetch + ] + elif compiled.update_prefetch: + prefetch_recs = [ + ( + c, + key_getter(c), + c._onupdate_description_tuple, + self.get_update_default, + ) + for c in compiled.update_prefetch + ] + else: + prefetch_recs = [] + + for param in self.compiled_parameters: + self.current_parameters = param + + for ( + c, + param_key, + (arg, is_scalar, is_callable, is_sentinel), + fallback, + ) in prefetch_recs: + if is_sentinel: + param[param_key] = sentinel_counter + sentinel_counter += 1 + elif is_scalar: + param[param_key] = arg + elif is_callable: + self.current_column = c + param[param_key] = arg(self) + else: + val = fallback(c) + if val is not None: + param[param_key] = val + + del self.current_parameters + + +DefaultDialect.execution_ctx_cls = DefaultExecutionContext diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/events.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/events.py new file mode 100644 index 0000000000000000000000000000000000000000..347afdf558f195a9bb5c9f3fdd8d6bbdfefdf3d0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/events.py @@ -0,0 +1,965 @@ +# engine/events.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + + +from __future__ import annotations + +import typing +from typing import Any +from typing import Dict +from typing import Optional +from typing import Tuple +from typing import Type +from typing import Union + +from .base import Connection +from .base import Engine +from .interfaces import ConnectionEventsTarget +from .interfaces import DBAPIConnection +from .interfaces import DBAPICursor +from .interfaces import Dialect +from .. import event +from .. import exc +from ..util.typing import Literal + +if typing.TYPE_CHECKING: + from .interfaces import _CoreMultiExecuteParams + from .interfaces import _CoreSingleExecuteParams + from .interfaces import _DBAPIAnyExecuteParams + from .interfaces import _DBAPIMultiExecuteParams + from .interfaces import _DBAPISingleExecuteParams + from .interfaces import _ExecuteOptions + from .interfaces import ExceptionContext + from .interfaces import ExecutionContext + from .result import Result + from ..pool import ConnectionPoolEntry + from ..sql import Executable + from ..sql.elements import BindParameter + + +class ConnectionEvents(event.Events[ConnectionEventsTarget]): + """Available events for + :class:`_engine.Connection` and :class:`_engine.Engine`. + + The methods here define the name of an event as well as the names of + members that are passed to listener functions. + + An event listener can be associated with any + :class:`_engine.Connection` or :class:`_engine.Engine` + class or instance, such as an :class:`_engine.Engine`, e.g.:: + + from sqlalchemy import event, create_engine + + + def before_cursor_execute( + conn, cursor, statement, parameters, context, executemany + ): + log.info("Received statement: %s", statement) + + + engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") + event.listen(engine, "before_cursor_execute", before_cursor_execute) + + or with a specific :class:`_engine.Connection`:: + + with engine.begin() as conn: + + @event.listens_for(conn, "before_cursor_execute") + def before_cursor_execute( + conn, cursor, statement, parameters, context, executemany + ): + log.info("Received statement: %s", statement) + + When the methods are called with a `statement` parameter, such as in + :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`, + the statement is the exact SQL string that was prepared for transmission + to the DBAPI ``cursor`` in the connection's :class:`.Dialect`. + + The :meth:`.before_execute` and :meth:`.before_cursor_execute` + events can also be established with the ``retval=True`` flag, which + allows modification of the statement and parameters to be sent + to the database. The :meth:`.before_cursor_execute` event is + particularly useful here to add ad-hoc string transformations, such + as comments, to all executions:: + + from sqlalchemy.engine import Engine + from sqlalchemy import event + + + @event.listens_for(Engine, "before_cursor_execute", retval=True) + def comment_sql_calls( + conn, cursor, statement, parameters, context, executemany + ): + statement = statement + " -- some comment" + return statement, parameters + + .. note:: :class:`_events.ConnectionEvents` can be established on any + combination of :class:`_engine.Engine`, :class:`_engine.Connection`, + as well + as instances of each of those classes. Events across all + four scopes will fire off for a given instance of + :class:`_engine.Connection`. However, for performance reasons, the + :class:`_engine.Connection` object determines at instantiation time + whether or not its parent :class:`_engine.Engine` has event listeners + established. Event listeners added to the :class:`_engine.Engine` + class or to an instance of :class:`_engine.Engine` + *after* the instantiation + of a dependent :class:`_engine.Connection` instance will usually + *not* be available on that :class:`_engine.Connection` instance. + The newly + added listeners will instead take effect for + :class:`_engine.Connection` + instances created subsequent to those event listeners being + established on the parent :class:`_engine.Engine` class or instance. + + :param retval=False: Applies to the :meth:`.before_execute` and + :meth:`.before_cursor_execute` events only. When True, the + user-defined event function must have a return value, which + is a tuple of parameters that replace the given statement + and parameters. See those methods for a description of + specific return arguments. + + """ # noqa + + _target_class_doc = "SomeEngine" + _dispatch_target = ConnectionEventsTarget + + @classmethod + def _accept_with( + cls, + target: Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]], + identifier: str, + ) -> Optional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]]: + default_dispatch = super()._accept_with(target, identifier) + if default_dispatch is None and hasattr( + target, "_no_async_engine_events" + ): + target._no_async_engine_events() + + return default_dispatch + + @classmethod + def _listen( + cls, + event_key: event._EventKey[ConnectionEventsTarget], + *, + retval: bool = False, + **kw: Any, + ) -> None: + target, identifier, fn = ( + event_key.dispatch_target, + event_key.identifier, + event_key._listen_fn, + ) + target._has_events = True + + if not retval: + if identifier == "before_execute": + orig_fn = fn + + def wrap_before_execute( # type: ignore + conn, clauseelement, multiparams, params, execution_options + ): + orig_fn( + conn, + clauseelement, + multiparams, + params, + execution_options, + ) + return clauseelement, multiparams, params + + fn = wrap_before_execute + elif identifier == "before_cursor_execute": + orig_fn = fn + + def wrap_before_cursor_execute( # type: ignore + conn, cursor, statement, parameters, context, executemany + ): + orig_fn( + conn, + cursor, + statement, + parameters, + context, + executemany, + ) + return statement, parameters + + fn = wrap_before_cursor_execute + elif retval and identifier not in ( + "before_execute", + "before_cursor_execute", + ): + raise exc.ArgumentError( + "Only the 'before_execute', " + "'before_cursor_execute' and 'handle_error' engine " + "event listeners accept the 'retval=True' " + "argument." + ) + event_key.with_wrapper(fn).base_listen() + + @event._legacy_signature( + "1.4", + ["conn", "clauseelement", "multiparams", "params"], + lambda conn, clauseelement, multiparams, params, execution_options: ( + conn, + clauseelement, + multiparams, + params, + ), + ) + def before_execute( + self, + conn: Connection, + clauseelement: Executable, + multiparams: _CoreMultiExecuteParams, + params: _CoreSingleExecuteParams, + execution_options: _ExecuteOptions, + ) -> Optional[ + Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams] + ]: + """Intercept high level execute() events, receiving uncompiled + SQL constructs and other objects prior to rendering into SQL. + + This event is good for debugging SQL compilation issues as well + as early manipulation of the parameters being sent to the database, + as the parameter lists will be in a consistent format here. + + This event can be optionally established with the ``retval=True`` + flag. The ``clauseelement``, ``multiparams``, and ``params`` + arguments should be returned as a three-tuple in this case:: + + @event.listens_for(Engine, "before_execute", retval=True) + def before_execute(conn, clauseelement, multiparams, params): + # do something with clauseelement, multiparams, params + return clauseelement, multiparams, params + + :param conn: :class:`_engine.Connection` object + :param clauseelement: SQL expression construct, :class:`.Compiled` + instance, or string statement passed to + :meth:`_engine.Connection.execute`. + :param multiparams: Multiple parameter sets, a list of dictionaries. + :param params: Single parameter set, a single dictionary. + :param execution_options: dictionary of execution + options passed along with the statement, if any. This is a merge + of all options that will be used, including those of the statement, + the connection, and those passed in to the method itself for + the 2.0 style of execution. + + .. versionadded: 1.4 + + .. seealso:: + + :meth:`.before_cursor_execute` + + """ + + @event._legacy_signature( + "1.4", + ["conn", "clauseelement", "multiparams", "params", "result"], + lambda conn, clauseelement, multiparams, params, execution_options, result: ( # noqa + conn, + clauseelement, + multiparams, + params, + result, + ), + ) + def after_execute( + self, + conn: Connection, + clauseelement: Executable, + multiparams: _CoreMultiExecuteParams, + params: _CoreSingleExecuteParams, + execution_options: _ExecuteOptions, + result: Result[Any], + ) -> None: + """Intercept high level execute() events after execute. + + + :param conn: :class:`_engine.Connection` object + :param clauseelement: SQL expression construct, :class:`.Compiled` + instance, or string statement passed to + :meth:`_engine.Connection.execute`. + :param multiparams: Multiple parameter sets, a list of dictionaries. + :param params: Single parameter set, a single dictionary. + :param execution_options: dictionary of execution + options passed along with the statement, if any. This is a merge + of all options that will be used, including those of the statement, + the connection, and those passed in to the method itself for + the 2.0 style of execution. + + .. versionadded: 1.4 + + :param result: :class:`_engine.CursorResult` generated by the + execution. + + """ + + def before_cursor_execute( + self, + conn: Connection, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIAnyExecuteParams, + context: Optional[ExecutionContext], + executemany: bool, + ) -> Optional[Tuple[str, _DBAPIAnyExecuteParams]]: + """Intercept low-level cursor execute() events before execution, + receiving the string SQL statement and DBAPI-specific parameter list to + be invoked against a cursor. + + This event is a good choice for logging as well as late modifications + to the SQL string. It's less ideal for parameter modifications except + for those which are specific to a target backend. + + This event can be optionally established with the ``retval=True`` + flag. The ``statement`` and ``parameters`` arguments should be + returned as a two-tuple in this case:: + + @event.listens_for(Engine, "before_cursor_execute", retval=True) + def before_cursor_execute( + conn, cursor, statement, parameters, context, executemany + ): + # do something with statement, parameters + return statement, parameters + + See the example at :class:`_events.ConnectionEvents`. + + :param conn: :class:`_engine.Connection` object + :param cursor: DBAPI cursor object + :param statement: string SQL statement, as to be passed to the DBAPI + :param parameters: Dictionary, tuple, or list of parameters being + passed to the ``execute()`` or ``executemany()`` method of the + DBAPI ``cursor``. In some cases may be ``None``. + :param context: :class:`.ExecutionContext` object in use. May + be ``None``. + :param executemany: boolean, if ``True``, this is an ``executemany()`` + call, if ``False``, this is an ``execute()`` call. + + .. seealso:: + + :meth:`.before_execute` + + :meth:`.after_cursor_execute` + + """ + + def after_cursor_execute( + self, + conn: Connection, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIAnyExecuteParams, + context: Optional[ExecutionContext], + executemany: bool, + ) -> None: + """Intercept low-level cursor execute() events after execution. + + :param conn: :class:`_engine.Connection` object + :param cursor: DBAPI cursor object. Will have results pending + if the statement was a SELECT, but these should not be consumed + as they will be needed by the :class:`_engine.CursorResult`. + :param statement: string SQL statement, as passed to the DBAPI + :param parameters: Dictionary, tuple, or list of parameters being + passed to the ``execute()`` or ``executemany()`` method of the + DBAPI ``cursor``. In some cases may be ``None``. + :param context: :class:`.ExecutionContext` object in use. May + be ``None``. + :param executemany: boolean, if ``True``, this is an ``executemany()`` + call, if ``False``, this is an ``execute()`` call. + + """ + + @event._legacy_signature( + "2.0", ["conn", "branch"], converter=lambda conn: (conn, False) + ) + def engine_connect(self, conn: Connection) -> None: + """Intercept the creation of a new :class:`_engine.Connection`. + + This event is called typically as the direct result of calling + the :meth:`_engine.Engine.connect` method. + + It differs from the :meth:`_events.PoolEvents.connect` method, which + refers to the actual connection to a database at the DBAPI level; + a DBAPI connection may be pooled and reused for many operations. + In contrast, this event refers only to the production of a higher level + :class:`_engine.Connection` wrapper around such a DBAPI connection. + + It also differs from the :meth:`_events.PoolEvents.checkout` event + in that it is specific to the :class:`_engine.Connection` object, + not the + DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with, + although + this DBAPI connection is available here via the + :attr:`_engine.Connection.connection` attribute. + But note there can in fact + be multiple :meth:`_events.PoolEvents.checkout` + events within the lifespan + of a single :class:`_engine.Connection` object, if that + :class:`_engine.Connection` + is invalidated and re-established. + + :param conn: :class:`_engine.Connection` object. + + .. seealso:: + + :meth:`_events.PoolEvents.checkout` + the lower-level pool checkout event + for an individual DBAPI connection + + """ + + def set_connection_execution_options( + self, conn: Connection, opts: Dict[str, Any] + ) -> None: + """Intercept when the :meth:`_engine.Connection.execution_options` + method is called. + + This method is called after the new :class:`_engine.Connection` + has been + produced, with the newly updated execution options collection, but + before the :class:`.Dialect` has acted upon any of those new options. + + Note that this method is not called when a new + :class:`_engine.Connection` + is produced which is inheriting execution options from its parent + :class:`_engine.Engine`; to intercept this condition, use the + :meth:`_events.ConnectionEvents.engine_connect` event. + + :param conn: The newly copied :class:`_engine.Connection` object + + :param opts: dictionary of options that were passed to the + :meth:`_engine.Connection.execution_options` method. + This dictionary may be modified in place to affect the ultimate + options which take effect. + + .. versionadded:: 2.0 the ``opts`` dictionary may be modified + in place. + + + .. seealso:: + + :meth:`_events.ConnectionEvents.set_engine_execution_options` + - event + which is called when :meth:`_engine.Engine.execution_options` + is called. + + + """ + + def set_engine_execution_options( + self, engine: Engine, opts: Dict[str, Any] + ) -> None: + """Intercept when the :meth:`_engine.Engine.execution_options` + method is called. + + The :meth:`_engine.Engine.execution_options` method produces a shallow + copy of the :class:`_engine.Engine` which stores the new options. + That new + :class:`_engine.Engine` is passed here. + A particular application of this + method is to add a :meth:`_events.ConnectionEvents.engine_connect` + event + handler to the given :class:`_engine.Engine` + which will perform some per- + :class:`_engine.Connection` task specific to these execution options. + + :param conn: The newly copied :class:`_engine.Engine` object + + :param opts: dictionary of options that were passed to the + :meth:`_engine.Connection.execution_options` method. + This dictionary may be modified in place to affect the ultimate + options which take effect. + + .. versionadded:: 2.0 the ``opts`` dictionary may be modified + in place. + + .. seealso:: + + :meth:`_events.ConnectionEvents.set_connection_execution_options` + - event + which is called when :meth:`_engine.Connection.execution_options` + is + called. + + """ + + def engine_disposed(self, engine: Engine) -> None: + """Intercept when the :meth:`_engine.Engine.dispose` method is called. + + The :meth:`_engine.Engine.dispose` method instructs the engine to + "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and + replaces it with a new one. Disposing of the old pool has the + effect that existing checked-in connections are closed. The new + pool does not establish any new connections until it is first used. + + This event can be used to indicate that resources related to the + :class:`_engine.Engine` should also be cleaned up, + keeping in mind that the + :class:`_engine.Engine` + can still be used for new requests in which case + it re-acquires connection resources. + + """ + + def begin(self, conn: Connection) -> None: + """Intercept begin() events. + + :param conn: :class:`_engine.Connection` object + + """ + + def rollback(self, conn: Connection) -> None: + """Intercept rollback() events, as initiated by a + :class:`.Transaction`. + + Note that the :class:`_pool.Pool` also "auto-rolls back" + a DBAPI connection upon checkin, if the ``reset_on_return`` + flag is set to its default value of ``'rollback'``. + To intercept this + rollback, use the :meth:`_events.PoolEvents.reset` hook. + + :param conn: :class:`_engine.Connection` object + + .. seealso:: + + :meth:`_events.PoolEvents.reset` + + """ + + def commit(self, conn: Connection) -> None: + """Intercept commit() events, as initiated by a + :class:`.Transaction`. + + Note that the :class:`_pool.Pool` may also "auto-commit" + a DBAPI connection upon checkin, if the ``reset_on_return`` + flag is set to the value ``'commit'``. To intercept this + commit, use the :meth:`_events.PoolEvents.reset` hook. + + :param conn: :class:`_engine.Connection` object + """ + + def savepoint(self, conn: Connection, name: str) -> None: + """Intercept savepoint() events. + + :param conn: :class:`_engine.Connection` object + :param name: specified name used for the savepoint. + + """ + + def rollback_savepoint( + self, conn: Connection, name: str, context: None + ) -> None: + """Intercept rollback_savepoint() events. + + :param conn: :class:`_engine.Connection` object + :param name: specified name used for the savepoint. + :param context: not used + + """ + # TODO: deprecate "context" + + def release_savepoint( + self, conn: Connection, name: str, context: None + ) -> None: + """Intercept release_savepoint() events. + + :param conn: :class:`_engine.Connection` object + :param name: specified name used for the savepoint. + :param context: not used + + """ + # TODO: deprecate "context" + + def begin_twophase(self, conn: Connection, xid: Any) -> None: + """Intercept begin_twophase() events. + + :param conn: :class:`_engine.Connection` object + :param xid: two-phase XID identifier + + """ + + def prepare_twophase(self, conn: Connection, xid: Any) -> None: + """Intercept prepare_twophase() events. + + :param conn: :class:`_engine.Connection` object + :param xid: two-phase XID identifier + """ + + def rollback_twophase( + self, conn: Connection, xid: Any, is_prepared: bool + ) -> None: + """Intercept rollback_twophase() events. + + :param conn: :class:`_engine.Connection` object + :param xid: two-phase XID identifier + :param is_prepared: boolean, indicates if + :meth:`.TwoPhaseTransaction.prepare` was called. + + """ + + def commit_twophase( + self, conn: Connection, xid: Any, is_prepared: bool + ) -> None: + """Intercept commit_twophase() events. + + :param conn: :class:`_engine.Connection` object + :param xid: two-phase XID identifier + :param is_prepared: boolean, indicates if + :meth:`.TwoPhaseTransaction.prepare` was called. + + """ + + +class DialectEvents(event.Events[Dialect]): + """event interface for execution-replacement functions. + + These events allow direct instrumentation and replacement + of key dialect functions which interact with the DBAPI. + + .. note:: + + :class:`.DialectEvents` hooks should be considered **semi-public** + and experimental. + These hooks are not for general use and are only for those situations + where intricate re-statement of DBAPI mechanics must be injected onto + an existing dialect. For general-use statement-interception events, + please use the :class:`_events.ConnectionEvents` interface. + + .. seealso:: + + :meth:`_events.ConnectionEvents.before_cursor_execute` + + :meth:`_events.ConnectionEvents.before_execute` + + :meth:`_events.ConnectionEvents.after_cursor_execute` + + :meth:`_events.ConnectionEvents.after_execute` + + """ + + _target_class_doc = "SomeEngine" + _dispatch_target = Dialect + + @classmethod + def _listen( + cls, + event_key: event._EventKey[Dialect], + *, + retval: bool = False, + **kw: Any, + ) -> None: + target = event_key.dispatch_target + + target._has_events = True + event_key.base_listen() + + @classmethod + def _accept_with( + cls, + target: Union[Engine, Type[Engine], Dialect, Type[Dialect]], + identifier: str, + ) -> Optional[Union[Dialect, Type[Dialect]]]: + if isinstance(target, type): + if issubclass(target, Engine): + return Dialect + elif issubclass(target, Dialect): + return target + elif isinstance(target, Engine): + return target.dialect + elif isinstance(target, Dialect): + return target + elif isinstance(target, Connection) and identifier == "handle_error": + raise exc.InvalidRequestError( + "The handle_error() event hook as of SQLAlchemy 2.0 is " + "established on the Dialect, and may only be applied to the " + "Engine as a whole or to a specific Dialect as a whole, " + "not on a per-Connection basis." + ) + elif hasattr(target, "_no_async_engine_events"): + target._no_async_engine_events() + else: + return None + + def handle_error( + self, exception_context: ExceptionContext + ) -> Optional[BaseException]: + r"""Intercept all exceptions processed by the + :class:`_engine.Dialect`, typically but not limited to those + emitted within the scope of a :class:`_engine.Connection`. + + .. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event + is moved to the :class:`.DialectEvents` class, moved from the + :class:`.ConnectionEvents` class, so that it may also participate in + the "pre ping" operation configured with the + :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event + remains registered by using the :class:`_engine.Engine` as the event + target, however note that using the :class:`_engine.Connection` as + an event target for :meth:`.DialectEvents.handle_error` is no longer + supported. + + This includes all exceptions emitted by the DBAPI as well as + within SQLAlchemy's statement invocation process, including + encoding errors and other statement validation errors. Other areas + in which the event is invoked include transaction begin and end, + result row fetching, cursor creation. + + Note that :meth:`.handle_error` may support new kinds of exceptions + and new calling scenarios at *any time*. Code which uses this + event must expect new calling patterns to be present in minor + releases. + + To support the wide variety of members that correspond to an exception, + as well as to allow extensibility of the event without backwards + incompatibility, the sole argument received is an instance of + :class:`.ExceptionContext`. This object contains data members + representing detail about the exception. + + Use cases supported by this hook include: + + * read-only, low-level exception handling for logging and + debugging purposes + * Establishing whether a DBAPI connection error message indicates + that the database connection needs to be reconnected, including + for the "pre_ping" handler used by **some** dialects + * Establishing or disabling whether a connection or the owning + connection pool is invalidated or expired in response to a + specific exception + * exception re-writing + + The hook is called while the cursor from the failed operation + (if any) is still open and accessible. Special cleanup operations + can be called on this cursor; SQLAlchemy will attempt to close + this cursor subsequent to this hook being invoked. + + As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the + :paramref:`_sa.create_engine.pool_pre_ping` parameter will also + participate in the :meth:`.handle_error` process, **for those dialects + that rely upon disconnect codes to detect database liveness**. Note + that some dialects such as psycopg, psycopg2, and most MySQL dialects + make use of a native ``ping()`` method supplied by the DBAPI which does + not make use of disconnect codes. + + .. versionchanged:: 2.0.0 The :meth:`.DialectEvents.handle_error` + event hook participates in connection pool "pre-ping" operations. + Within this usage, the :attr:`.ExceptionContext.engine` attribute + will be ``None``, however the :class:`.Dialect` in use is always + available via the :attr:`.ExceptionContext.dialect` attribute. + + .. versionchanged:: 2.0.5 Added :attr:`.ExceptionContext.is_pre_ping` + attribute which will be set to ``True`` when the + :meth:`.DialectEvents.handle_error` event hook is triggered within + a connection pool pre-ping operation. + + .. versionchanged:: 2.0.5 An issue was repaired that allows for the + PostgreSQL ``psycopg`` and ``psycopg2`` drivers, as well as all + MySQL drivers, to properly participate in the + :meth:`.DialectEvents.handle_error` event hook during + connection pool "pre-ping" operations; previously, the + implementation was non-working for these drivers. + + + A handler function has two options for replacing + the SQLAlchemy-constructed exception into one that is user + defined. It can either raise this new exception directly, in + which case all further event listeners are bypassed and the + exception will be raised, after appropriate cleanup as taken + place:: + + @event.listens_for(Engine, "handle_error") + def handle_exception(context): + if isinstance( + context.original_exception, psycopg2.OperationalError + ) and "failed" in str(context.original_exception): + raise MySpecialException("failed operation") + + .. warning:: Because the + :meth:`_events.DialectEvents.handle_error` + event specifically provides for exceptions to be re-thrown as + the ultimate exception raised by the failed statement, + **stack traces will be misleading** if the user-defined event + handler itself fails and throws an unexpected exception; + the stack trace may not illustrate the actual code line that + failed! It is advised to code carefully here and use + logging and/or inline debugging if unexpected exceptions are + occurring. + + Alternatively, a "chained" style of event handling can be + used, by configuring the handler with the ``retval=True`` + modifier and returning the new exception instance from the + function. In this case, event handling will continue onto the + next handler. The "chained" exception is available using + :attr:`.ExceptionContext.chained_exception`:: + + @event.listens_for(Engine, "handle_error", retval=True) + def handle_exception(context): + if ( + context.chained_exception is not None + and "special" in context.chained_exception.message + ): + return MySpecialException( + "failed", cause=context.chained_exception + ) + + Handlers that return ``None`` may be used within the chain; when + a handler returns ``None``, the previous exception instance, + if any, is maintained as the current exception that is passed onto the + next handler. + + When a custom exception is raised or returned, SQLAlchemy raises + this new exception as-is, it is not wrapped by any SQLAlchemy + object. If the exception is not a subclass of + :class:`sqlalchemy.exc.StatementError`, + certain features may not be available; currently this includes + the ORM's feature of adding a detail hint about "autoflush" to + exceptions raised within the autoflush process. + + :param context: an :class:`.ExceptionContext` object. See this + class for details on all available members. + + + .. seealso:: + + :ref:`pool_new_disconnect_codes` + + """ + + def do_connect( + self, + dialect: Dialect, + conn_rec: ConnectionPoolEntry, + cargs: Tuple[Any, ...], + cparams: Dict[str, Any], + ) -> Optional[DBAPIConnection]: + """Receive connection arguments before a connection is made. + + This event is useful in that it allows the handler to manipulate the + cargs and/or cparams collections that control how the DBAPI + ``connect()`` function will be called. ``cargs`` will always be a + Python list that can be mutated in-place, and ``cparams`` a Python + dictionary that may also be mutated:: + + e = create_engine("postgresql+psycopg2://user@host/dbname") + + + @event.listens_for(e, "do_connect") + def receive_do_connect(dialect, conn_rec, cargs, cparams): + cparams["password"] = "some_password" + + The event hook may also be used to override the call to ``connect()`` + entirely, by returning a non-``None`` DBAPI connection object:: + + e = create_engine("postgresql+psycopg2://user@host/dbname") + + + @event.listens_for(e, "do_connect") + def receive_do_connect(dialect, conn_rec, cargs, cparams): + return psycopg2.connect(*cargs, **cparams) + + .. seealso:: + + :ref:`custom_dbapi_args` + + """ + + def do_executemany( + self, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIMultiExecuteParams, + context: ExecutionContext, + ) -> Optional[Literal[True]]: + """Receive a cursor to have executemany() called. + + Return the value True to halt further events from invoking, + and to indicate that the cursor execution has already taken + place within the event handler. + + """ + + def do_execute_no_params( + self, cursor: DBAPICursor, statement: str, context: ExecutionContext + ) -> Optional[Literal[True]]: + """Receive a cursor to have execute() with no parameters called. + + Return the value True to halt further events from invoking, + and to indicate that the cursor execution has already taken + place within the event handler. + + """ + + def do_execute( + self, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPISingleExecuteParams, + context: ExecutionContext, + ) -> Optional[Literal[True]]: + """Receive a cursor to have execute() called. + + Return the value True to halt further events from invoking, + and to indicate that the cursor execution has already taken + place within the event handler. + + """ + + def do_setinputsizes( + self, + inputsizes: Dict[BindParameter[Any], Any], + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIAnyExecuteParams, + context: ExecutionContext, + ) -> None: + """Receive the setinputsizes dictionary for possible modification. + + This event is emitted in the case where the dialect makes use of the + DBAPI ``cursor.setinputsizes()`` method which passes information about + parameter binding for a particular statement. The given + ``inputsizes`` dictionary will contain :class:`.BindParameter` objects + as keys, linked to DBAPI-specific type objects as values; for + parameters that are not bound, they are added to the dictionary with + ``None`` as the value, which means the parameter will not be included + in the ultimate setinputsizes call. The event may be used to inspect + and/or log the datatypes that are being bound, as well as to modify the + dictionary in place. Parameters can be added, modified, or removed + from this dictionary. Callers will typically want to inspect the + :attr:`.BindParameter.type` attribute of the given bind objects in + order to make decisions about the DBAPI object. + + After the event, the ``inputsizes`` dictionary is converted into + an appropriate datastructure to be passed to ``cursor.setinputsizes``; + either a list for a positional bound parameter execution style, + or a dictionary of string parameter keys to DBAPI type objects for + a named bound parameter execution style. + + The setinputsizes hook overall is only used for dialects which include + the flag ``use_setinputsizes=True``. Dialects which use this + include python-oracledb, cx_Oracle, pg8000, asyncpg, and pyodbc + dialects. + + .. note:: + + For use with pyodbc, the ``use_setinputsizes`` flag + must be passed to the dialect, e.g.:: + + create_engine("mssql+pyodbc://...", use_setinputsizes=True) + + .. seealso:: + + :ref:`mssql_pyodbc_setinputsizes` + + .. versionadded:: 1.2.9 + + .. seealso:: + + :ref:`cx_oracle_setinputsizes` + + """ + pass diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/interfaces.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0b48cbe23700ad5ca94cab9cbf9363952ec121 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/interfaces.py @@ -0,0 +1,3471 @@ +# engine/interfaces.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Define core interfaces used by the engine system.""" + +from __future__ import annotations + +from enum import Enum +from typing import Any +from typing import Awaitable +from typing import Callable +from typing import ClassVar +from typing import Collection +from typing import Dict +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .. import util +from ..event import EventTarget +from ..pool import Pool +from ..pool import PoolProxiedConnection as PoolProxiedConnection +from ..sql.compiler import Compiled as Compiled +from ..sql.compiler import Compiled # noqa +from ..sql.compiler import TypeCompiler as TypeCompiler +from ..sql.compiler import TypeCompiler # noqa +from ..util import immutabledict +from ..util.concurrency import await_only +from ..util.typing import Literal +from ..util.typing import NotRequired +from ..util.typing import Protocol +from ..util.typing import TypedDict + +if TYPE_CHECKING: + from .base import Connection + from .base import Engine + from .cursor import CursorResult + from .url import URL + from ..connectors.asyncio import AsyncIODBAPIConnection + from ..event import _ListenerFnType + from ..event import dispatcher + from ..exc import StatementError + from ..sql import Executable + from ..sql.compiler import _InsertManyValuesBatch + from ..sql.compiler import DDLCompiler + from ..sql.compiler import IdentifierPreparer + from ..sql.compiler import InsertmanyvaluesSentinelOpts + from ..sql.compiler import Linting + from ..sql.compiler import SQLCompiler + from ..sql.elements import BindParameter + from ..sql.elements import ClauseElement + from ..sql.schema import Column + from ..sql.schema import DefaultGenerator + from ..sql.schema import SchemaItem + from ..sql.schema import Sequence as Sequence_SchemaItem + from ..sql.sqltypes import Integer + from ..sql.type_api import _TypeMemoDict + from ..sql.type_api import TypeEngine + from ..util.langhelpers import generic_fn_descriptor + +ConnectArgsType = Tuple[Sequence[str], MutableMapping[str, Any]] + +_T = TypeVar("_T", bound="Any") + + +class CacheStats(Enum): + CACHE_HIT = 0 + CACHE_MISS = 1 + CACHING_DISABLED = 2 + NO_CACHE_KEY = 3 + NO_DIALECT_SUPPORT = 4 + + +class ExecuteStyle(Enum): + """indicates the :term:`DBAPI` cursor method that will be used to invoke + a statement.""" + + EXECUTE = 0 + """indicates cursor.execute() will be used""" + + EXECUTEMANY = 1 + """indicates cursor.executemany() will be used.""" + + INSERTMANYVALUES = 2 + """indicates cursor.execute() will be used with an INSERT where the + VALUES expression will be expanded to accommodate for multiple + parameter sets + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + """ + + +class DBAPIModule(Protocol): + class Error(Exception): + def __getattr__(self, key: str) -> Any: ... + + class OperationalError(Error): + pass + + class InterfaceError(Error): + pass + + class IntegrityError(Error): + pass + + def __getattr__(self, key: str) -> Any: ... + + +class DBAPIConnection(Protocol): + """protocol representing a :pep:`249` database connection. + + .. versionadded:: 2.0 + + .. seealso:: + + `Connection Objects `_ + - in :pep:`249` + + """ # noqa: E501 + + def close(self) -> None: ... + + def commit(self) -> None: ... + + def cursor(self, *args: Any, **kwargs: Any) -> DBAPICursor: ... + + def rollback(self) -> None: ... + + def __getattr__(self, key: str) -> Any: ... + + def __setattr__(self, key: str, value: Any) -> None: ... + + +class DBAPIType(Protocol): + """protocol representing a :pep:`249` database type. + + .. versionadded:: 2.0 + + .. seealso:: + + `Type Objects `_ + - in :pep:`249` + + """ # noqa: E501 + + +class DBAPICursor(Protocol): + """protocol representing a :pep:`249` database cursor. + + .. versionadded:: 2.0 + + .. seealso:: + + `Cursor Objects `_ + - in :pep:`249` + + """ # noqa: E501 + + @property + def description( + self, + ) -> _DBAPICursorDescription: + """The description attribute of the Cursor. + + .. seealso:: + + `cursor.description `_ + - in :pep:`249` + + + """ # noqa: E501 + ... + + @property + def rowcount(self) -> int: ... + + arraysize: int + + lastrowid: int + + def close(self) -> None: ... + + def execute( + self, + operation: Any, + parameters: Optional[_DBAPISingleExecuteParams] = None, + ) -> Any: ... + + def executemany( + self, + operation: Any, + parameters: _DBAPIMultiExecuteParams, + ) -> Any: ... + + def fetchone(self) -> Optional[Any]: ... + + def fetchmany(self, size: int = ...) -> Sequence[Any]: ... + + def fetchall(self) -> Sequence[Any]: ... + + def setinputsizes(self, sizes: Sequence[Any]) -> None: ... + + def setoutputsize(self, size: Any, column: Any) -> None: ... + + def callproc( + self, procname: str, parameters: Sequence[Any] = ... + ) -> Any: ... + + def nextset(self) -> Optional[bool]: ... + + def __getattr__(self, key: str) -> Any: ... + + +_CoreSingleExecuteParams = Mapping[str, Any] +_MutableCoreSingleExecuteParams = MutableMapping[str, Any] +_CoreMultiExecuteParams = Sequence[_CoreSingleExecuteParams] +_CoreAnyExecuteParams = Union[ + _CoreMultiExecuteParams, _CoreSingleExecuteParams +] + +_DBAPISingleExecuteParams = Union[Sequence[Any], _CoreSingleExecuteParams] + +_DBAPIMultiExecuteParams = Union[ + Sequence[Sequence[Any]], _CoreMultiExecuteParams +] +_DBAPIAnyExecuteParams = Union[ + _DBAPIMultiExecuteParams, _DBAPISingleExecuteParams +] +_DBAPICursorDescription = Sequence[ + Tuple[ + str, + "DBAPIType", + Optional[int], + Optional[int], + Optional[int], + Optional[int], + Optional[bool], + ] +] + +_AnySingleExecuteParams = _DBAPISingleExecuteParams +_AnyMultiExecuteParams = _DBAPIMultiExecuteParams +_AnyExecuteParams = _DBAPIAnyExecuteParams + +CompiledCacheType = MutableMapping[Any, "Compiled"] +SchemaTranslateMapType = Mapping[Optional[str], Optional[str]] + +_ImmutableExecuteOptions = immutabledict[str, Any] + +_ParamStyle = Literal[ + "qmark", "numeric", "named", "format", "pyformat", "numeric_dollar" +] + +_GenericSetInputSizesType = List[Tuple[str, Any, "TypeEngine[Any]"]] + +IsolationLevel = Literal[ + "SERIALIZABLE", + "REPEATABLE READ", + "READ COMMITTED", + "READ UNCOMMITTED", + "AUTOCOMMIT", +] + + +class _CoreKnownExecutionOptions(TypedDict, total=False): + compiled_cache: Optional[CompiledCacheType] + logging_token: str + isolation_level: IsolationLevel + no_parameters: bool + stream_results: bool + max_row_buffer: int + yield_per: int + insertmanyvalues_page_size: int + schema_translate_map: Optional[SchemaTranslateMapType] + preserve_rowcount: bool + + +_ExecuteOptions = immutabledict[str, Any] +CoreExecuteOptionsParameter = Union[ + _CoreKnownExecutionOptions, Mapping[str, Any] +] + + +class ReflectedIdentity(TypedDict): + """represent the reflected IDENTITY structure of a column, corresponding + to the :class:`_schema.Identity` construct. + + The :class:`.ReflectedIdentity` structure is part of the + :class:`.ReflectedColumn` structure, which is returned by the + :meth:`.Inspector.get_columns` method. + + """ + + always: bool + """type of identity column""" + + on_null: bool + """indicates ON NULL""" + + start: int + """starting index of the sequence""" + + increment: int + """increment value of the sequence""" + + minvalue: int + """the minimum value of the sequence.""" + + maxvalue: int + """the maximum value of the sequence.""" + + nominvalue: bool + """no minimum value of the sequence.""" + + nomaxvalue: bool + """no maximum value of the sequence.""" + + cycle: bool + """allows the sequence to wrap around when the maxvalue + or minvalue has been reached.""" + + cache: Optional[int] + """number of future values in the + sequence which are calculated in advance.""" + + order: bool + """if true, renders the ORDER keyword.""" + + +class ReflectedComputed(TypedDict): + """Represent the reflected elements of a computed column, corresponding + to the :class:`_schema.Computed` construct. + + The :class:`.ReflectedComputed` structure is part of the + :class:`.ReflectedColumn` structure, which is returned by the + :meth:`.Inspector.get_columns` method. + + """ + + sqltext: str + """the expression used to generate this column returned + as a string SQL expression""" + + persisted: NotRequired[bool] + """indicates if the value is stored in the table or computed on demand""" + + +class ReflectedColumn(TypedDict): + """Dictionary representing the reflected elements corresponding to + a :class:`_schema.Column` object. + + The :class:`.ReflectedColumn` structure is returned by the + :class:`.Inspector.get_columns` method. + + """ + + name: str + """column name""" + + type: TypeEngine[Any] + """column type represented as a :class:`.TypeEngine` instance.""" + + nullable: bool + """boolean flag if the column is NULL or NOT NULL""" + + default: Optional[str] + """column default expression as a SQL string""" + + autoincrement: NotRequired[bool] + """database-dependent autoincrement flag. + + This flag indicates if the column has a database-side "autoincrement" + flag of some kind. Within SQLAlchemy, other kinds of columns may + also act as an "autoincrement" column without necessarily having + such a flag on them. + + See :paramref:`_schema.Column.autoincrement` for more background on + "autoincrement". + + """ + + comment: NotRequired[Optional[str]] + """comment for the column, if present. + Only some dialects return this key + """ + + computed: NotRequired[ReflectedComputed] + """indicates that this column is computed by the database. + Only some dialects return this key. + + .. versionadded:: 1.3.16 - added support for computed reflection. + """ + + identity: NotRequired[ReflectedIdentity] + """indicates this column is an IDENTITY column. + Only some dialects return this key. + + .. versionadded:: 1.4 - added support for identity column reflection. + """ + + dialect_options: NotRequired[Dict[str, Any]] + """Additional dialect-specific options detected for this reflected + object""" + + +class ReflectedConstraint(TypedDict): + """Dictionary representing the reflected elements corresponding to + :class:`.Constraint` + + A base class for all constraints + """ + + name: Optional[str] + """constraint name""" + + comment: NotRequired[Optional[str]] + """comment for the constraint, if present""" + + +class ReflectedCheckConstraint(ReflectedConstraint): + """Dictionary representing the reflected elements corresponding to + :class:`.CheckConstraint`. + + The :class:`.ReflectedCheckConstraint` structure is returned by the + :meth:`.Inspector.get_check_constraints` method. + + """ + + sqltext: str + """the check constraint's SQL expression""" + + dialect_options: NotRequired[Dict[str, Any]] + """Additional dialect-specific options detected for this check constraint + + .. versionadded:: 1.3.8 + """ + + +class ReflectedUniqueConstraint(ReflectedConstraint): + """Dictionary representing the reflected elements corresponding to + :class:`.UniqueConstraint`. + + The :class:`.ReflectedUniqueConstraint` structure is returned by the + :meth:`.Inspector.get_unique_constraints` method. + + """ + + column_names: List[str] + """column names which comprise the unique constraint""" + + duplicates_index: NotRequired[Optional[str]] + "Indicates if this unique constraint duplicates an index with this name" + + dialect_options: NotRequired[Dict[str, Any]] + """Additional dialect-specific options detected for this unique + constraint""" + + +class ReflectedPrimaryKeyConstraint(ReflectedConstraint): + """Dictionary representing the reflected elements corresponding to + :class:`.PrimaryKeyConstraint`. + + The :class:`.ReflectedPrimaryKeyConstraint` structure is returned by the + :meth:`.Inspector.get_pk_constraint` method. + + """ + + constrained_columns: List[str] + """column names which comprise the primary key""" + + dialect_options: NotRequired[Dict[str, Any]] + """Additional dialect-specific options detected for this primary key""" + + +class ReflectedForeignKeyConstraint(ReflectedConstraint): + """Dictionary representing the reflected elements corresponding to + :class:`.ForeignKeyConstraint`. + + The :class:`.ReflectedForeignKeyConstraint` structure is returned by + the :meth:`.Inspector.get_foreign_keys` method. + + """ + + constrained_columns: List[str] + """local column names which comprise the foreign key""" + + referred_schema: Optional[str] + """schema name of the table being referred""" + + referred_table: str + """name of the table being referred""" + + referred_columns: List[str] + """referred column names that correspond to ``constrained_columns``""" + + options: NotRequired[Dict[str, Any]] + """Additional options detected for this foreign key constraint""" + + +class ReflectedIndex(TypedDict): + """Dictionary representing the reflected elements corresponding to + :class:`.Index`. + + The :class:`.ReflectedIndex` structure is returned by the + :meth:`.Inspector.get_indexes` method. + + """ + + name: Optional[str] + """index name""" + + column_names: List[Optional[str]] + """column names which the index references. + An element of this list is ``None`` if it's an expression and is + returned in the ``expressions`` list. + """ + + expressions: NotRequired[List[str]] + """Expressions that compose the index. This list, when present, contains + both plain column names (that are also in ``column_names``) and + expressions (that are ``None`` in ``column_names``). + """ + + unique: bool + """whether or not the index has a unique flag""" + + duplicates_constraint: NotRequired[Optional[str]] + "Indicates if this index mirrors a constraint with this name" + + include_columns: NotRequired[List[str]] + """columns to include in the INCLUDE clause for supporting databases. + + .. deprecated:: 2.0 + + Legacy value, will be replaced with + ``index_dict["dialect_options"]["_include"]`` + + """ + + column_sorting: NotRequired[Dict[str, Tuple[str]]] + """optional dict mapping column names or expressions to tuple of sort + keywords, which may include ``asc``, ``desc``, ``nulls_first``, + ``nulls_last``. + + .. versionadded:: 1.3.5 + """ + + dialect_options: NotRequired[Dict[str, Any]] + """Additional dialect-specific options detected for this index""" + + +class ReflectedTableComment(TypedDict): + """Dictionary representing the reflected comment corresponding to + the :attr:`_schema.Table.comment` attribute. + + The :class:`.ReflectedTableComment` structure is returned by the + :meth:`.Inspector.get_table_comment` method. + + """ + + text: Optional[str] + """text of the comment""" + + +class BindTyping(Enum): + """Define different methods of passing typing information for + bound parameters in a statement to the database driver. + + .. versionadded:: 2.0 + + """ + + NONE = 1 + """No steps are taken to pass typing information to the database driver. + + This is the default behavior for databases such as SQLite, MySQL / MariaDB, + SQL Server. + + """ + + SETINPUTSIZES = 2 + """Use the pep-249 setinputsizes method. + + This is only implemented for DBAPIs that support this method and for which + the SQLAlchemy dialect has the appropriate infrastructure for that dialect + set up. Current dialects include python-oracledb, cx_Oracle as well as + optional support for SQL Server using pyodbc. + + When using setinputsizes, dialects also have a means of only using the + method for certain datatypes using include/exclude lists. + + When SETINPUTSIZES is used, the :meth:`.Dialect.do_set_input_sizes` method + is called for each statement executed which has bound parameters. + + """ + + RENDER_CASTS = 3 + """Render casts or other directives in the SQL string. + + This method is used for all PostgreSQL dialects, including asyncpg, + pg8000, psycopg, psycopg2. Dialects which implement this can choose + which kinds of datatypes are explicitly cast in SQL statements and which + aren't. + + When RENDER_CASTS is used, the compiler will invoke the + :meth:`.SQLCompiler.render_bind_cast` method for the rendered + string representation of each :class:`.BindParameter` object whose + dialect-level type sets the :attr:`.TypeEngine.render_bind_cast` attribute. + + The :meth:`.SQLCompiler.render_bind_cast` is also used to render casts + for one form of "insertmanyvalues" query, when both + :attr:`.InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT` and + :attr:`.InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS` are set, + where the casts are applied to the intermediary columns e.g. + "INSERT INTO t (a, b, c) SELECT p0::TYP, p1::TYP, p2::TYP " + "FROM (VALUES (?, ?), (?, ?), ...)". + + .. versionadded:: 2.0.10 - :meth:`.SQLCompiler.render_bind_cast` is now + used within some elements of the "insertmanyvalues" implementation. + + + """ + + +VersionInfoType = Tuple[Union[int, str], ...] +TableKey = Tuple[Optional[str], str] + + +class Dialect(EventTarget): + """Define the behavior of a specific database and DB-API combination. + + Any aspect of metadata definition, SQL query generation, + execution, result-set handling, or anything else which varies + between databases is defined under the general category of the + Dialect. The Dialect acts as a factory for other + database-specific object implementations including + ExecutionContext, Compiled, DefaultGenerator, and TypeEngine. + + .. note:: Third party dialects should not subclass :class:`.Dialect` + directly. Instead, subclass :class:`.default.DefaultDialect` or + descendant class. + + """ + + CACHE_HIT = CacheStats.CACHE_HIT + CACHE_MISS = CacheStats.CACHE_MISS + CACHING_DISABLED = CacheStats.CACHING_DISABLED + NO_CACHE_KEY = CacheStats.NO_CACHE_KEY + NO_DIALECT_SUPPORT = CacheStats.NO_DIALECT_SUPPORT + + dispatch: dispatcher[Dialect] + + name: str + """identifying name for the dialect from a DBAPI-neutral point of view + (i.e. 'sqlite') + """ + + driver: str + """identifying name for the dialect's DBAPI""" + + dialect_description: str + + dbapi: Optional[DBAPIModule] + """A reference to the DBAPI module object itself. + + SQLAlchemy dialects import DBAPI modules using the classmethod + :meth:`.Dialect.import_dbapi`. The rationale is so that any dialect + module can be imported and used to generate SQL statements without the + need for the actual DBAPI driver to be installed. Only when an + :class:`.Engine` is constructed using :func:`.create_engine` does the + DBAPI get imported; at that point, the creation process will assign + the DBAPI module to this attribute. + + Dialects should therefore implement :meth:`.Dialect.import_dbapi` + which will import the necessary module and return it, and then refer + to ``self.dbapi`` in dialect code in order to refer to the DBAPI module + contents. + + .. versionchanged:: The :attr:`.Dialect.dbapi` attribute is exclusively + used as the per-:class:`.Dialect`-instance reference to the DBAPI + module. The previous not-fully-documented ``.Dialect.dbapi()`` + classmethod is deprecated and replaced by :meth:`.Dialect.import_dbapi`. + + """ + + @util.non_memoized_property + def loaded_dbapi(self) -> DBAPIModule: + """same as .dbapi, but is never None; will raise an error if no + DBAPI was set up. + + .. versionadded:: 2.0 + + """ + raise NotImplementedError() + + positional: bool + """True if the paramstyle for this Dialect is positional.""" + + paramstyle: str + """the paramstyle to be used (some DB-APIs support multiple + paramstyles). + """ + + compiler_linting: Linting + + statement_compiler: Type[SQLCompiler] + """a :class:`.Compiled` class used to compile SQL statements""" + + ddl_compiler: Type[DDLCompiler] + """a :class:`.Compiled` class used to compile DDL statements""" + + type_compiler_cls: ClassVar[Type[TypeCompiler]] + """a :class:`.Compiled` class used to compile SQL type objects + + .. versionadded:: 2.0 + + """ + + type_compiler_instance: TypeCompiler + """instance of a :class:`.Compiled` class used to compile SQL type + objects + + .. versionadded:: 2.0 + + """ + + type_compiler: Any + """legacy; this is a TypeCompiler class at the class level, a + TypeCompiler instance at the instance level. + + Refer to type_compiler_instance instead. + + """ + + preparer: Type[IdentifierPreparer] + """a :class:`.IdentifierPreparer` class used to + quote identifiers. + """ + + identifier_preparer: IdentifierPreparer + """This element will refer to an instance of :class:`.IdentifierPreparer` + once a :class:`.DefaultDialect` has been constructed. + + """ + + server_version_info: Optional[Tuple[Any, ...]] + """a tuple containing a version number for the DB backend in use. + + This value is only available for supporting dialects, and is + typically populated during the initial connection to the database. + """ + + default_schema_name: Optional[str] + """the name of the default schema. This value is only available for + supporting dialects, and is typically populated during the + initial connection to the database. + + """ + + # NOTE: this does not take into effect engine-level isolation level. + # not clear if this should be changed, seems like it should + default_isolation_level: Optional[IsolationLevel] + """the isolation that is implicitly present on new connections""" + + skip_autocommit_rollback: bool + """Whether or not the :paramref:`.create_engine.skip_autocommit_rollback` + parameter was set. + + .. versionadded:: 2.0.43 + + """ + + # create_engine() -> isolation_level currently goes here + _on_connect_isolation_level: Optional[IsolationLevel] + + execution_ctx_cls: Type[ExecutionContext] + """a :class:`.ExecutionContext` class used to handle statement execution""" + + execute_sequence_format: Union[ + Type[Tuple[Any, ...]], Type[Tuple[List[Any]]] + ] + """either the 'tuple' or 'list' type, depending on what cursor.execute() + accepts for the second argument (they vary).""" + + supports_alter: bool + """``True`` if the database supports ``ALTER TABLE`` - used only for + generating foreign key constraints in certain circumstances + """ + + max_identifier_length: int + """The maximum length of identifier names.""" + max_index_name_length: Optional[int] + """The maximum length of index names if different from + ``max_identifier_length``.""" + max_constraint_name_length: Optional[int] + """The maximum length of constraint names if different from + ``max_identifier_length``.""" + + supports_server_side_cursors: Union[generic_fn_descriptor[bool], bool] + """indicates if the dialect supports server side cursors""" + + server_side_cursors: bool + """deprecated; indicates if the dialect should attempt to use server + side cursors by default""" + + supports_sane_rowcount: bool + """Indicate whether the dialect properly implements rowcount for + ``UPDATE`` and ``DELETE`` statements. + """ + + supports_sane_multi_rowcount: bool + """Indicate whether the dialect properly implements rowcount for + ``UPDATE`` and ``DELETE`` statements when executed via + executemany. + """ + + supports_empty_insert: bool + """dialect supports INSERT () VALUES (), i.e. a plain INSERT with no + columns in it. + + This is not usually supported; an "empty" insert is typically + suited using either "INSERT..DEFAULT VALUES" or + "INSERT ... (col) VALUES (DEFAULT)". + + """ + + supports_default_values: bool + """dialect supports INSERT... DEFAULT VALUES syntax""" + + supports_default_metavalue: bool + """dialect supports INSERT...(col) VALUES (DEFAULT) syntax. + + Most databases support this in some way, e.g. SQLite supports it using + ``VALUES (NULL)``. MS SQL Server supports the syntax also however + is the only included dialect where we have this disabled, as + MSSQL does not support the field for the IDENTITY column, which is + usually where we like to make use of the feature. + + """ + + default_metavalue_token: str = "DEFAULT" + """for INSERT... VALUES (DEFAULT) syntax, the token to put in the + parenthesis. + + E.g. for SQLite this is the keyword "NULL". + + """ + + supports_multivalues_insert: bool + """Target database supports INSERT...VALUES with multiple value + sets, i.e. INSERT INTO table (cols) VALUES (...), (...), (...), ... + + """ + + insert_executemany_returning: bool + """dialect / driver / database supports some means of providing + INSERT...RETURNING support when dialect.do_executemany() is used. + + """ + + insert_executemany_returning_sort_by_parameter_order: bool + """dialect / driver / database supports some means of providing + INSERT...RETURNING support when dialect.do_executemany() is used + along with the :paramref:`_dml.Insert.returning.sort_by_parameter_order` + parameter being set. + + """ + + update_executemany_returning: bool + """dialect supports UPDATE..RETURNING with executemany.""" + + delete_executemany_returning: bool + """dialect supports DELETE..RETURNING with executemany.""" + + use_insertmanyvalues: bool + """if True, indicates "insertmanyvalues" functionality should be used + to allow for ``insert_executemany_returning`` behavior, if possible. + + In practice, setting this to True means: + + if ``supports_multivalues_insert``, ``insert_returning`` and + ``use_insertmanyvalues`` are all True, the SQL compiler will produce + an INSERT that will be interpreted by the :class:`.DefaultDialect` + as an :attr:`.ExecuteStyle.INSERTMANYVALUES` execution that allows + for INSERT of many rows with RETURNING by rewriting a single-row + INSERT statement to have multiple VALUES clauses, also executing + the statement multiple times for a series of batches when large numbers + of rows are given. + + The parameter is False for the default dialect, and is set to True for + SQLAlchemy internal dialects SQLite, MySQL/MariaDB, PostgreSQL, SQL Server. + It remains at False for Oracle Database, which provides native "executemany + with RETURNING" support and also does not support + ``supports_multivalues_insert``. For MySQL/MariaDB, those MySQL dialects + that don't support RETURNING will not report + ``insert_executemany_returning`` as True. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + """ + + use_insertmanyvalues_wo_returning: bool + """if True, and use_insertmanyvalues is also True, INSERT statements + that don't include RETURNING will also use "insertmanyvalues". + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`engine_insertmanyvalues` + + """ + + insertmanyvalues_implicit_sentinel: InsertmanyvaluesSentinelOpts + """Options indicating the database supports a form of bulk INSERT where + the autoincrement integer primary key can be reliably used as an ordering + for INSERTed rows. + + .. versionadded:: 2.0.10 + + .. seealso:: + + :ref:`engine_insertmanyvalues_returning_order` + + """ + + insertmanyvalues_page_size: int + """Number of rows to render into an individual INSERT..VALUES() statement + for :attr:`.ExecuteStyle.INSERTMANYVALUES` executions. + + The default dialect defaults this to 1000. + + .. versionadded:: 2.0 + + .. seealso:: + + :paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size` - + execution option available on :class:`_engine.Connection`, statements + + """ # noqa: E501 + + insertmanyvalues_max_parameters: int + """Alternate to insertmanyvalues_page_size, will additionally limit + page size based on number of parameters total in the statement. + + + """ + + preexecute_autoincrement_sequences: bool + """True if 'implicit' primary key functions must be executed separately + in order to get their value, if RETURNING is not used. + + This is currently oriented towards PostgreSQL when the + ``implicit_returning=False`` parameter is used on a :class:`.Table` + object. + + """ + + insert_returning: bool + """if the dialect supports RETURNING with INSERT + + .. versionadded:: 2.0 + + """ + + update_returning: bool + """if the dialect supports RETURNING with UPDATE + + .. versionadded:: 2.0 + + """ + + update_returning_multifrom: bool + """if the dialect supports RETURNING with UPDATE..FROM + + .. versionadded:: 2.0 + + """ + + delete_returning: bool + """if the dialect supports RETURNING with DELETE + + .. versionadded:: 2.0 + + """ + + delete_returning_multifrom: bool + """if the dialect supports RETURNING with DELETE..FROM + + .. versionadded:: 2.0 + + """ + + favor_returning_over_lastrowid: bool + """for backends that support both a lastrowid and a RETURNING insert + strategy, favor RETURNING for simple single-int pk inserts. + + cursor.lastrowid tends to be more performant on most backends. + + """ + + supports_identity_columns: bool + """target database supports IDENTITY""" + + cte_follows_insert: bool + """target database, when given a CTE with an INSERT statement, needs + the CTE to be below the INSERT""" + + colspecs: MutableMapping[Type[TypeEngine[Any]], Type[TypeEngine[Any]]] + """A dictionary of TypeEngine classes from sqlalchemy.types mapped + to subclasses that are specific to the dialect class. This + dictionary is class-level only and is not accessed from the + dialect instance itself. + """ + + supports_sequences: bool + """Indicates if the dialect supports CREATE SEQUENCE or similar.""" + + sequences_optional: bool + """If True, indicates if the :paramref:`_schema.Sequence.optional` + parameter on the :class:`_schema.Sequence` construct + should signal to not generate a CREATE SEQUENCE. Applies only to + dialects that support sequences. Currently used only to allow PostgreSQL + SERIAL to be used on a column that specifies Sequence() for usage on + other backends. + """ + + default_sequence_base: int + """the default value that will be rendered as the "START WITH" portion of + a CREATE SEQUENCE DDL statement. + + """ + + supports_native_enum: bool + """Indicates if the dialect supports a native ENUM construct. + This will prevent :class:`_types.Enum` from generating a CHECK + constraint when that type is used in "native" mode. + """ + + supports_native_boolean: bool + """Indicates if the dialect supports a native boolean construct. + This will prevent :class:`_types.Boolean` from generating a CHECK + constraint when that type is used. + """ + + supports_native_decimal: bool + """indicates if Decimal objects are handled and returned for precision + numeric types, or if floats are returned""" + + supports_native_uuid: bool + """indicates if Python UUID() objects are handled natively by the + driver for SQL UUID datatypes. + + .. versionadded:: 2.0 + + """ + + returns_native_bytes: bool + """indicates if Python bytes() objects are returned natively by the + driver for SQL "binary" datatypes. + + .. versionadded:: 2.0.11 + + """ + + construct_arguments: Optional[ + List[Tuple[Type[Union[SchemaItem, ClauseElement]], Mapping[str, Any]]] + ] = None + """Optional set of argument specifiers for various SQLAlchemy + constructs, typically schema items. + + To implement, establish as a series of tuples, as in:: + + construct_arguments = [ + (schema.Index, {"using": False, "where": None, "ops": None}), + ] + + If the above construct is established on the PostgreSQL dialect, + the :class:`.Index` construct will now accept the keyword arguments + ``postgresql_using``, ``postgresql_where``, nad ``postgresql_ops``. + Any other argument specified to the constructor of :class:`.Index` + which is prefixed with ``postgresql_`` will raise :class:`.ArgumentError`. + + A dialect which does not include a ``construct_arguments`` member will + not participate in the argument validation system. For such a dialect, + any argument name is accepted by all participating constructs, within + the namespace of arguments prefixed with that dialect name. The rationale + here is so that third-party dialects that haven't yet implemented this + feature continue to function in the old way. + + .. seealso:: + + :class:`.DialectKWArgs` - implementing base class which consumes + :attr:`.DefaultDialect.construct_arguments` + + + """ + + reflection_options: Sequence[str] = () + """Sequence of string names indicating keyword arguments that can be + established on a :class:`.Table` object which will be passed as + "reflection options" when using :paramref:`.Table.autoload_with`. + + Current example is "oracle_resolve_synonyms" in the Oracle Database + dialects. + + """ + + dbapi_exception_translation_map: Mapping[str, str] = util.EMPTY_DICT + """A dictionary of names that will contain as values the names of + pep-249 exceptions ("IntegrityError", "OperationalError", etc) + keyed to alternate class names, to support the case where a + DBAPI has exception classes that aren't named as they are + referred to (e.g. IntegrityError = MyException). In the vast + majority of cases this dictionary is empty. + """ + + supports_comments: bool + """Indicates the dialect supports comment DDL on tables and columns.""" + + inline_comments: bool + """Indicates the dialect supports comment DDL that's inline with the + definition of a Table or Column. If False, this implies that ALTER must + be used to set table and column comments.""" + + supports_constraint_comments: bool + """Indicates if the dialect supports comment DDL on constraints. + + .. versionadded:: 2.0 + """ + + _has_events = False + + supports_statement_cache: bool = True + """indicates if this dialect supports caching. + + All dialects that are compatible with statement caching should set this + flag to True directly on each dialect class and subclass that supports + it. SQLAlchemy tests that this flag is locally present on each dialect + subclass before it will use statement caching. This is to provide + safety for legacy or new dialects that are not yet fully tested to be + compliant with SQL statement caching. + + .. versionadded:: 1.4.5 + + .. seealso:: + + :ref:`engine_thirdparty_caching` + + """ + + _supports_statement_cache: bool + """internal evaluation for supports_statement_cache""" + + bind_typing = BindTyping.NONE + """define a means of passing typing information to the database and/or + driver for bound parameters. + + See :class:`.BindTyping` for values. + + .. versionadded:: 2.0 + + """ + + is_async: bool + """Whether or not this dialect is intended for asyncio use.""" + + has_terminate: bool + """Whether or not this dialect has a separate "terminate" implementation + that does not block or require awaiting.""" + + engine_config_types: Mapping[str, Any] + """a mapping of string keys that can be in an engine config linked to + type conversion functions. + + """ + + label_length: Optional[int] + """optional user-defined max length for SQL labels""" + + include_set_input_sizes: Optional[Set[Any]] + """set of DBAPI type objects that should be included in + automatic cursor.setinputsizes() calls. + + This is only used if bind_typing is BindTyping.SET_INPUT_SIZES + + """ + + exclude_set_input_sizes: Optional[Set[Any]] + """set of DBAPI type objects that should be excluded in + automatic cursor.setinputsizes() calls. + + This is only used if bind_typing is BindTyping.SET_INPUT_SIZES + + """ + + supports_simple_order_by_label: bool + """target database supports ORDER BY , where + refers to a label in the columns clause of the SELECT""" + + div_is_floordiv: bool + """target database treats the / division operator as "floor division" """ + + tuple_in_values: bool + """target database supports tuple IN, i.e. (x, y) IN ((q, p), (r, z))""" + + requires_name_normalize: bool + """Indicates symbol names are returned by the database in + UPPERCASED if they are case insensitive within the database. + If this is True, the methods normalize_name() + and denormalize_name() must be provided. + """ + + _bind_typing_render_casts: bool + + _type_memos: MutableMapping[TypeEngine[Any], _TypeMemoDict] + + def _builtin_onconnect(self) -> Optional[_ListenerFnType]: + raise NotImplementedError() + + def create_connect_args(self, url: URL) -> ConnectArgsType: + """Build DB-API compatible connection arguments. + + Given a :class:`.URL` object, returns a tuple + consisting of a ``(*args, **kwargs)`` suitable to send directly + to the dbapi's connect function. The arguments are sent to the + :meth:`.Dialect.connect` method which then runs the DBAPI-level + ``connect()`` function. + + The method typically makes use of the + :meth:`.URL.translate_connect_args` + method in order to generate a dictionary of options. + + The default implementation is:: + + def create_connect_args(self, url): + opts = url.translate_connect_args() + opts.update(url.query) + return ([], opts) + + :param url: a :class:`.URL` object + + :return: a tuple of ``(*args, **kwargs)`` which will be passed to the + :meth:`.Dialect.connect` method. + + .. seealso:: + + :meth:`.URL.translate_connect_args` + + """ + + raise NotImplementedError() + + @classmethod + def import_dbapi(cls) -> DBAPIModule: + """Import the DBAPI module that is used by this dialect. + + The Python module object returned here will be assigned as an + instance variable to a constructed dialect under the name + ``.dbapi``. + + .. versionchanged:: 2.0 The :meth:`.Dialect.import_dbapi` class + method is renamed from the previous method ``.Dialect.dbapi()``, + which would be replaced at dialect instantiation time by the + DBAPI module itself, thus using the same name in two different ways. + If a ``.Dialect.dbapi()`` classmethod is present on a third-party + dialect, it will be used and a deprecation warning will be emitted. + + """ + raise NotImplementedError() + + def type_descriptor(self, typeobj: TypeEngine[_T]) -> TypeEngine[_T]: + """Transform a generic type to a dialect-specific type. + + Dialect classes will usually use the + :func:`_types.adapt_type` function in the types module to + accomplish this. + + The returned result is cached *per dialect class* so can + contain no dialect-instance state. + + """ + + raise NotImplementedError() + + def initialize(self, connection: Connection) -> None: + """Called during strategized creation of the dialect with a + connection. + + Allows dialects to configure options based on server version info or + other properties. + + The connection passed here is a SQLAlchemy Connection object, + with full capabilities. + + The initialize() method of the base dialect should be called via + super(). + + .. note:: as of SQLAlchemy 1.4, this method is called **before** + any :meth:`_engine.Dialect.on_connect` hooks are called. + + """ + + if TYPE_CHECKING: + + def _overrides_default(self, method_name: str) -> bool: ... + + def get_columns( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> List[ReflectedColumn]: + """Return information about columns in ``table_name``. + + Given a :class:`_engine.Connection`, a string + ``table_name``, and an optional string ``schema``, return column + information as a list of dictionaries + corresponding to the :class:`.ReflectedColumn` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_columns`. + + """ + + raise NotImplementedError() + + def get_multi_columns( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, List[ReflectedColumn]]]: + """Return information about columns in all tables in the + given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_multi_columns`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_pk_constraint( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> ReflectedPrimaryKeyConstraint: + """Return information about the primary key constraint on + table_name`. + + Given a :class:`_engine.Connection`, a string + ``table_name``, and an optional string ``schema``, return primary + key information as a dictionary corresponding to the + :class:`.ReflectedPrimaryKeyConstraint` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_pk_constraint`. + + """ + raise NotImplementedError() + + def get_multi_pk_constraint( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, ReflectedPrimaryKeyConstraint]]: + """Return information about primary key constraints in + all tables in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_multi_pk_constraint`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + raise NotImplementedError() + + def get_foreign_keys( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> List[ReflectedForeignKeyConstraint]: + """Return information about foreign_keys in ``table_name``. + + Given a :class:`_engine.Connection`, a string + ``table_name``, and an optional string ``schema``, return foreign + key information as a list of dicts corresponding to the + :class:`.ReflectedForeignKeyConstraint` dictionary. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_foreign_keys`. + """ + + raise NotImplementedError() + + def get_multi_foreign_keys( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, List[ReflectedForeignKeyConstraint]]]: + """Return information about foreign_keys in all tables + in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_multi_foreign_keys`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_table_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of table names for ``schema``. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_table_names`. + + """ + + raise NotImplementedError() + + def get_temp_table_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of temporary table names on the given connection, + if supported by the underlying backend. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_temp_table_names`. + + """ + + raise NotImplementedError() + + def get_view_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of all non-materialized view names available in the + database. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_view_names`. + + :param schema: schema name to query, if not the default schema. + + """ + + raise NotImplementedError() + + def get_materialized_view_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of all materialized view names available in the + database. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_materialized_view_names`. + + :param schema: schema name to query, if not the default schema. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_sequence_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of all sequence names available in the database. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_sequence_names`. + + :param schema: schema name to query, if not the default schema. + + .. versionadded:: 1.4 + """ + + raise NotImplementedError() + + def get_temp_view_names( + self, connection: Connection, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + """Return a list of temporary view names on the given connection, + if supported by the underlying backend. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_temp_view_names`. + + """ + + raise NotImplementedError() + + def get_schema_names(self, connection: Connection, **kw: Any) -> List[str]: + """Return a list of all schema names available in the database. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_schema_names`. + """ + raise NotImplementedError() + + def get_view_definition( + self, + connection: Connection, + view_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> str: + """Return plain or materialized view definition. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_view_definition`. + + Given a :class:`_engine.Connection`, a string + ``view_name``, and an optional string ``schema``, return the view + definition. + """ + + raise NotImplementedError() + + def get_indexes( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> List[ReflectedIndex]: + """Return information about indexes in ``table_name``. + + Given a :class:`_engine.Connection`, a string + ``table_name`` and an optional string ``schema``, return index + information as a list of dictionaries corresponding to the + :class:`.ReflectedIndex` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_indexes`. + """ + + raise NotImplementedError() + + def get_multi_indexes( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, List[ReflectedIndex]]]: + """Return information about indexes in in all tables + in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_multi_indexes`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_unique_constraints( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> List[ReflectedUniqueConstraint]: + r"""Return information about unique constraints in ``table_name``. + + Given a string ``table_name`` and an optional string ``schema``, return + unique constraint information as a list of dicts corresponding + to the :class:`.ReflectedUniqueConstraint` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_unique_constraints`. + """ + + raise NotImplementedError() + + def get_multi_unique_constraints( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, List[ReflectedUniqueConstraint]]]: + """Return information about unique constraints in all tables + in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_multi_unique_constraints`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_check_constraints( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> List[ReflectedCheckConstraint]: + r"""Return information about check constraints in ``table_name``. + + Given a string ``table_name`` and an optional string ``schema``, return + check constraint information as a list of dicts corresponding + to the :class:`.ReflectedCheckConstraint` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_check_constraints`. + + """ + + raise NotImplementedError() + + def get_multi_check_constraints( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, List[ReflectedCheckConstraint]]]: + """Return information about check constraints in all tables + in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_multi_check_constraints`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def get_table_options( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> Dict[str, Any]: + """Return a dictionary of options specified when ``table_name`` + was created. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_table_options`. + """ + raise NotImplementedError() + + def get_multi_table_options( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, Dict[str, Any]]]: + """Return a dictionary of options specified when the tables in the + given schema were created. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_multi_table_options`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + raise NotImplementedError() + + def get_table_comment( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> ReflectedTableComment: + r"""Return the "comment" for the table identified by ``table_name``. + + Given a string ``table_name`` and an optional string ``schema``, return + table comment information as a dictionary corresponding to the + :class:`.ReflectedTableComment` dictionary. + + This is an internal dialect method. Applications should use + :meth:`.Inspector.get_table_comment`. + + :raise: ``NotImplementedError`` for dialects that don't support + comments. + + .. versionadded:: 1.2 + + """ + + raise NotImplementedError() + + def get_multi_table_comment( + self, + connection: Connection, + *, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + **kw: Any, + ) -> Iterable[Tuple[TableKey, ReflectedTableComment]]: + """Return information about the table comment in all tables + in the given ``schema``. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.get_multi_table_comment`. + + .. note:: The :class:`_engine.DefaultDialect` provides a default + implementation that will call the single table method for + each object returned by :meth:`Dialect.get_table_names`, + :meth:`Dialect.get_view_names` or + :meth:`Dialect.get_materialized_view_names` depending on the + provided ``kind``. Dialects that want to support a faster + implementation should implement this method. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def normalize_name(self, name: str) -> str: + """convert the given name to lowercase if it is detected as + case insensitive. + + This method is only used if the dialect defines + requires_name_normalize=True. + + """ + raise NotImplementedError() + + def denormalize_name(self, name: str) -> str: + """convert the given name to a case insensitive identifier + for the backend if it is an all-lowercase name. + + This method is only used if the dialect defines + requires_name_normalize=True. + + """ + raise NotImplementedError() + + def has_table( + self, + connection: Connection, + table_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> bool: + """For internal dialect use, check the existence of a particular table + or view in the database. + + Given a :class:`_engine.Connection` object, a string table_name and + optional schema name, return True if the given table exists in the + database, False otherwise. + + This method serves as the underlying implementation of the + public facing :meth:`.Inspector.has_table` method, and is also used + internally to implement the "checkfirst" behavior for methods like + :meth:`_schema.Table.create` and :meth:`_schema.MetaData.create_all`. + + .. note:: This method is used internally by SQLAlchemy, and is + published so that third-party dialects may provide an + implementation. It is **not** the public API for checking for table + presence. Please use the :meth:`.Inspector.has_table` method. + + .. versionchanged:: 2.0:: :meth:`_engine.Dialect.has_table` now + formally supports checking for additional table-like objects: + + * any type of views (plain or materialized) + * temporary tables of any kind + + Previously, these two checks were not formally specified and + different dialects would vary in their behavior. The dialect + testing suite now includes tests for all of these object types, + and dialects to the degree that the backing database supports views + or temporary tables should seek to support locating these objects + for full compliance. + + """ + + raise NotImplementedError() + + def has_index( + self, + connection: Connection, + table_name: str, + index_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> bool: + """Check the existence of a particular index name in the database. + + Given a :class:`_engine.Connection` object, a string + ``table_name`` and string index name, return ``True`` if an index of + the given name on the given table exists, ``False`` otherwise. + + The :class:`.DefaultDialect` implements this in terms of the + :meth:`.Dialect.has_table` and :meth:`.Dialect.get_indexes` methods, + however dialects can implement a more performant version. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.has_index`. + + .. versionadded:: 1.4 + + """ + + raise NotImplementedError() + + def has_sequence( + self, + connection: Connection, + sequence_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> bool: + """Check the existence of a particular sequence in the database. + + Given a :class:`_engine.Connection` object and a string + `sequence_name`, return ``True`` if the given sequence exists in + the database, ``False`` otherwise. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.has_sequence`. + """ + + raise NotImplementedError() + + def has_schema( + self, connection: Connection, schema_name: str, **kw: Any + ) -> bool: + """Check the existence of a particular schema name in the database. + + Given a :class:`_engine.Connection` object, a string + ``schema_name``, return ``True`` if a schema of the + given exists, ``False`` otherwise. + + The :class:`.DefaultDialect` implements this by checking + the presence of ``schema_name`` among the schemas returned by + :meth:`.Dialect.get_schema_names`, + however dialects can implement a more performant version. + + This is an internal dialect method. Applications should use + :meth:`_engine.Inspector.has_schema`. + + .. versionadded:: 2.0 + + """ + + raise NotImplementedError() + + def _get_server_version_info(self, connection: Connection) -> Any: + """Retrieve the server version info from the given connection. + + This is used by the default implementation to populate the + "server_version_info" attribute and is called exactly + once upon first connect. + + """ + + raise NotImplementedError() + + def _get_default_schema_name(self, connection: Connection) -> str: + """Return the string name of the currently selected schema from + the given connection. + + This is used by the default implementation to populate the + "default_schema_name" attribute and is called exactly + once upon first connect. + + """ + + raise NotImplementedError() + + def do_begin(self, dbapi_connection: PoolProxiedConnection) -> None: + """Provide an implementation of ``connection.begin()``, given a + DB-API connection. + + The DBAPI has no dedicated "begin" method and it is expected + that transactions are implicit. This hook is provided for those + DBAPIs that might need additional help in this area. + + :param dbapi_connection: a DBAPI connection, typically + proxied within a :class:`.ConnectionFairy`. + + """ + + raise NotImplementedError() + + def do_rollback(self, dbapi_connection: PoolProxiedConnection) -> None: + """Provide an implementation of ``connection.rollback()``, given + a DB-API connection. + + :param dbapi_connection: a DBAPI connection, typically + proxied within a :class:`.ConnectionFairy`. + + """ + + raise NotImplementedError() + + def do_commit(self, dbapi_connection: PoolProxiedConnection) -> None: + """Provide an implementation of ``connection.commit()``, given a + DB-API connection. + + :param dbapi_connection: a DBAPI connection, typically + proxied within a :class:`.ConnectionFairy`. + + """ + + raise NotImplementedError() + + def do_terminate(self, dbapi_connection: DBAPIConnection) -> None: + """Provide an implementation of ``connection.close()`` that tries as + much as possible to not block, given a DBAPI + connection. + + In the vast majority of cases this just calls .close(), however + for some asyncio dialects may call upon different API features. + + This hook is called by the :class:`_pool.Pool` + when a connection is being recycled or has been invalidated. + + .. versionadded:: 1.4.41 + + """ + + raise NotImplementedError() + + def do_close(self, dbapi_connection: DBAPIConnection) -> None: + """Provide an implementation of ``connection.close()``, given a DBAPI + connection. + + This hook is called by the :class:`_pool.Pool` + when a connection has been + detached from the pool, or is being returned beyond the normal + capacity of the pool. + + """ + + raise NotImplementedError() + + def _do_ping_w_event(self, dbapi_connection: DBAPIConnection) -> bool: + raise NotImplementedError() + + def do_ping(self, dbapi_connection: DBAPIConnection) -> bool: + """ping the DBAPI connection and return True if the connection is + usable.""" + raise NotImplementedError() + + def do_set_input_sizes( + self, + cursor: DBAPICursor, + list_of_tuples: _GenericSetInputSizesType, + context: ExecutionContext, + ) -> Any: + """invoke the cursor.setinputsizes() method with appropriate arguments + + This hook is called if the :attr:`.Dialect.bind_typing` attribute is + set to the + :attr:`.BindTyping.SETINPUTSIZES` value. + Parameter data is passed in a list of tuples (paramname, dbtype, + sqltype), where ``paramname`` is the key of the parameter in the + statement, ``dbtype`` is the DBAPI datatype and ``sqltype`` is the + SQLAlchemy type. The order of tuples is in the correct parameter order. + + .. versionadded:: 1.4 + + .. versionchanged:: 2.0 - setinputsizes mode is now enabled by + setting :attr:`.Dialect.bind_typing` to + :attr:`.BindTyping.SETINPUTSIZES`. Dialects which accept + a ``use_setinputsizes`` parameter should set this value + appropriately. + + + """ + raise NotImplementedError() + + def create_xid(self) -> Any: + """Create a two-phase transaction ID. + + This id will be passed to do_begin_twophase(), + do_rollback_twophase(), do_commit_twophase(). Its format is + unspecified. + """ + + raise NotImplementedError() + + def do_savepoint(self, connection: Connection, name: str) -> None: + """Create a savepoint with the given name. + + :param connection: a :class:`_engine.Connection`. + :param name: savepoint name. + + """ + + raise NotImplementedError() + + def do_rollback_to_savepoint( + self, connection: Connection, name: str + ) -> None: + """Rollback a connection to the named savepoint. + + :param connection: a :class:`_engine.Connection`. + :param name: savepoint name. + + """ + + raise NotImplementedError() + + def do_release_savepoint(self, connection: Connection, name: str) -> None: + """Release the named savepoint on a connection. + + :param connection: a :class:`_engine.Connection`. + :param name: savepoint name. + """ + + raise NotImplementedError() + + def do_begin_twophase(self, connection: Connection, xid: Any) -> None: + """Begin a two phase transaction on the given connection. + + :param connection: a :class:`_engine.Connection`. + :param xid: xid + + """ + + raise NotImplementedError() + + def do_prepare_twophase(self, connection: Connection, xid: Any) -> None: + """Prepare a two phase transaction on the given connection. + + :param connection: a :class:`_engine.Connection`. + :param xid: xid + + """ + + raise NotImplementedError() + + def do_rollback_twophase( + self, + connection: Connection, + xid: Any, + is_prepared: bool = True, + recover: bool = False, + ) -> None: + """Rollback a two phase transaction on the given connection. + + :param connection: a :class:`_engine.Connection`. + :param xid: xid + :param is_prepared: whether or not + :meth:`.TwoPhaseTransaction.prepare` was called. + :param recover: if the recover flag was passed. + + """ + + raise NotImplementedError() + + def do_commit_twophase( + self, + connection: Connection, + xid: Any, + is_prepared: bool = True, + recover: bool = False, + ) -> None: + """Commit a two phase transaction on the given connection. + + + :param connection: a :class:`_engine.Connection`. + :param xid: xid + :param is_prepared: whether or not + :meth:`.TwoPhaseTransaction.prepare` was called. + :param recover: if the recover flag was passed. + + """ + + raise NotImplementedError() + + def do_recover_twophase(self, connection: Connection) -> List[Any]: + """Recover list of uncommitted prepared two phase transaction + identifiers on the given connection. + + :param connection: a :class:`_engine.Connection`. + + """ + + raise NotImplementedError() + + def _deliver_insertmanyvalues_batches( + self, + connection: Connection, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIMultiExecuteParams, + generic_setinputsizes: Optional[_GenericSetInputSizesType], + context: ExecutionContext, + ) -> Iterator[_InsertManyValuesBatch]: + """convert executemany parameters for an INSERT into an iterator + of statement/single execute values, used by the insertmanyvalues + feature. + + """ + raise NotImplementedError() + + def do_executemany( + self, + cursor: DBAPICursor, + statement: str, + parameters: _DBAPIMultiExecuteParams, + context: Optional[ExecutionContext] = None, + ) -> None: + """Provide an implementation of ``cursor.executemany(statement, + parameters)``.""" + + raise NotImplementedError() + + def do_execute( + self, + cursor: DBAPICursor, + statement: str, + parameters: Optional[_DBAPISingleExecuteParams], + context: Optional[ExecutionContext] = None, + ) -> None: + """Provide an implementation of ``cursor.execute(statement, + parameters)``.""" + + raise NotImplementedError() + + def do_execute_no_params( + self, + cursor: DBAPICursor, + statement: str, + context: Optional[ExecutionContext] = None, + ) -> None: + """Provide an implementation of ``cursor.execute(statement)``. + + The parameter collection should not be sent. + + """ + + raise NotImplementedError() + + def is_disconnect( + self, + e: DBAPIModule.Error, + connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]], + cursor: Optional[DBAPICursor], + ) -> bool: + """Return True if the given DB-API error indicates an invalid + connection""" + + raise NotImplementedError() + + def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection: + r"""Establish a connection using this dialect's DBAPI. + + The default implementation of this method is:: + + def connect(self, *cargs, **cparams): + return self.dbapi.connect(*cargs, **cparams) + + The ``*cargs, **cparams`` parameters are generated directly + from this dialect's :meth:`.Dialect.create_connect_args` method. + + This method may be used for dialects that need to perform programmatic + per-connection steps when a new connection is procured from the + DBAPI. + + + :param \*cargs: positional parameters returned from the + :meth:`.Dialect.create_connect_args` method + + :param \*\*cparams: keyword parameters returned from the + :meth:`.Dialect.create_connect_args` method. + + :return: a DBAPI connection, typically from the :pep:`249` module + level ``.connect()`` function. + + .. seealso:: + + :meth:`.Dialect.create_connect_args` + + :meth:`.Dialect.on_connect` + + """ + raise NotImplementedError() + + def on_connect_url(self, url: URL) -> Optional[Callable[[Any], Any]]: + """return a callable which sets up a newly created DBAPI connection. + + This method is a new hook that supersedes the + :meth:`_engine.Dialect.on_connect` method when implemented by a + dialect. When not implemented by a dialect, it invokes the + :meth:`_engine.Dialect.on_connect` method directly to maintain + compatibility with existing dialects. There is no deprecation + for :meth:`_engine.Dialect.on_connect` expected. + + The callable should accept a single argument "conn" which is the + DBAPI connection itself. The inner callable has no + return value. + + E.g.:: + + class MyDialect(default.DefaultDialect): + # ... + + def on_connect_url(self, url): + def do_on_connect(connection): + connection.execute("SET SPECIAL FLAGS etc") + + return do_on_connect + + This is used to set dialect-wide per-connection options such as + isolation modes, Unicode modes, etc. + + This method differs from :meth:`_engine.Dialect.on_connect` in that + it is passed the :class:`_engine.URL` object that's relevant to the + connect args. Normally the only way to get this is from the + :meth:`_engine.Dialect.on_connect` hook is to look on the + :class:`_engine.Engine` itself, however this URL object may have been + replaced by plugins. + + .. note:: + + The default implementation of + :meth:`_engine.Dialect.on_connect_url` is to invoke the + :meth:`_engine.Dialect.on_connect` method. Therefore if a dialect + implements this method, the :meth:`_engine.Dialect.on_connect` + method **will not be called** unless the overriding dialect calls + it directly from here. + + .. versionadded:: 1.4.3 added :meth:`_engine.Dialect.on_connect_url` + which normally calls into :meth:`_engine.Dialect.on_connect`. + + :param url: a :class:`_engine.URL` object representing the + :class:`_engine.URL` that was passed to the + :meth:`_engine.Dialect.create_connect_args` method. + + :return: a callable that accepts a single DBAPI connection as an + argument, or None. + + .. seealso:: + + :meth:`_engine.Dialect.on_connect` + + """ + return self.on_connect() + + def on_connect(self) -> Optional[Callable[[Any], None]]: + """return a callable which sets up a newly created DBAPI connection. + + The callable should accept a single argument "conn" which is the + DBAPI connection itself. The inner callable has no + return value. + + E.g.:: + + class MyDialect(default.DefaultDialect): + # ... + + def on_connect(self): + def do_on_connect(connection): + connection.execute("SET SPECIAL FLAGS etc") + + return do_on_connect + + This is used to set dialect-wide per-connection options such as + isolation modes, Unicode modes, etc. + + The "do_on_connect" callable is invoked by using the + :meth:`_events.PoolEvents.connect` event + hook, then unwrapping the DBAPI connection and passing it into the + callable. + + .. versionchanged:: 1.4 the on_connect hook is no longer called twice + for the first connection of a dialect. The on_connect hook is still + called before the :meth:`_engine.Dialect.initialize` method however. + + .. versionchanged:: 1.4.3 the on_connect hook is invoked from a new + method on_connect_url that passes the URL that was used to create + the connect args. Dialects can implement on_connect_url instead + of on_connect if they need the URL object that was used for the + connection in order to get additional context. + + If None is returned, no event listener is generated. + + :return: a callable that accepts a single DBAPI connection as an + argument, or None. + + .. seealso:: + + :meth:`.Dialect.connect` - allows the DBAPI ``connect()`` sequence + itself to be controlled. + + :meth:`.Dialect.on_connect_url` - supersedes + :meth:`.Dialect.on_connect` to also receive the + :class:`_engine.URL` object in context. + + """ + return None + + def reset_isolation_level(self, dbapi_connection: DBAPIConnection) -> None: + """Given a DBAPI connection, revert its isolation to the default. + + Note that this is a dialect-level method which is used as part + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` + isolation level facilities; these APIs should be preferred for + most typical use cases. + + .. seealso:: + + :meth:`_engine.Connection.get_isolation_level` + - view current level + + :attr:`_engine.Connection.default_isolation_level` + - view default level + + :paramref:`.Connection.execution_options.isolation_level` - + set per :class:`_engine.Connection` isolation level + + :paramref:`_sa.create_engine.isolation_level` - + set per :class:`_engine.Engine` isolation level + + """ + + raise NotImplementedError() + + def set_isolation_level( + self, dbapi_connection: DBAPIConnection, level: IsolationLevel + ) -> None: + """Given a DBAPI connection, set its isolation level. + + Note that this is a dialect-level method which is used as part + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` + isolation level facilities; these APIs should be preferred for + most typical use cases. + + If the dialect also implements the + :meth:`.Dialect.get_isolation_level_values` method, then the given + level is guaranteed to be one of the string names within that sequence, + and the method will not need to anticipate a lookup failure. + + .. seealso:: + + :meth:`_engine.Connection.get_isolation_level` + - view current level + + :attr:`_engine.Connection.default_isolation_level` + - view default level + + :paramref:`.Connection.execution_options.isolation_level` - + set per :class:`_engine.Connection` isolation level + + :paramref:`_sa.create_engine.isolation_level` - + set per :class:`_engine.Engine` isolation level + + """ + + raise NotImplementedError() + + def get_isolation_level( + self, dbapi_connection: DBAPIConnection + ) -> IsolationLevel: + """Given a DBAPI connection, return its isolation level. + + When working with a :class:`_engine.Connection` object, + the corresponding + DBAPI connection may be procured using the + :attr:`_engine.Connection.connection` accessor. + + Note that this is a dialect-level method which is used as part + of the implementation of the :class:`_engine.Connection` and + :class:`_engine.Engine` isolation level facilities; + these APIs should be preferred for most typical use cases. + + + .. seealso:: + + :meth:`_engine.Connection.get_isolation_level` + - view current level + + :attr:`_engine.Connection.default_isolation_level` + - view default level + + :paramref:`.Connection.execution_options.isolation_level` - + set per :class:`_engine.Connection` isolation level + + :paramref:`_sa.create_engine.isolation_level` - + set per :class:`_engine.Engine` isolation level + + + """ + + raise NotImplementedError() + + def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool: + """Detect the current autocommit setting for a DBAPI connection. + + :param dbapi_connection: a DBAPI connection object + :return: True if autocommit is enabled, False if disabled + :rtype: bool + + This method inspects the given DBAPI connection to determine + whether autocommit mode is currently enabled. The specific + mechanism for detecting autocommit varies by database dialect + and DBAPI driver, however it should be done **without** network + round trips. + + .. note:: + + Not all dialects support autocommit detection. Dialects + that do not support this feature will raise + :exc:`NotImplementedError`. + + """ + raise NotImplementedError( + "This dialect cannot detect autocommit on a DBAPI connection" + ) + + def get_default_isolation_level( + self, dbapi_conn: DBAPIConnection + ) -> IsolationLevel: + """Given a DBAPI connection, return its isolation level, or + a default isolation level if one cannot be retrieved. + + This method may only raise NotImplementedError and + **must not raise any other exception**, as it is used implicitly upon + first connect. + + The method **must return a value** for a dialect that supports + isolation level settings, as this level is what will be reverted + towards when a per-connection isolation level change is made. + + The method defaults to using the :meth:`.Dialect.get_isolation_level` + method unless overridden by a dialect. + + .. versionadded:: 1.3.22 + + """ + raise NotImplementedError() + + def get_isolation_level_values( + self, dbapi_conn: DBAPIConnection + ) -> Sequence[IsolationLevel]: + """return a sequence of string isolation level names that are accepted + by this dialect. + + The available names should use the following conventions: + + * use UPPERCASE names. isolation level methods will accept lowercase + names but these are normalized into UPPERCASE before being passed + along to the dialect. + * separate words should be separated by spaces, not underscores, e.g. + ``REPEATABLE READ``. isolation level names will have underscores + converted to spaces before being passed along to the dialect. + * The names for the four standard isolation names to the extent that + they are supported by the backend should be ``READ UNCOMMITTED``, + ``READ COMMITTED``, ``REPEATABLE READ``, ``SERIALIZABLE`` + * if the dialect supports an autocommit option it should be provided + using the isolation level name ``AUTOCOMMIT``. + * Other isolation modes may also be present, provided that they + are named in UPPERCASE and use spaces not underscores. + + This function is used so that the default dialect can check that + a given isolation level parameter is valid, else raises an + :class:`_exc.ArgumentError`. + + A DBAPI connection is passed to the method, in the unlikely event that + the dialect needs to interrogate the connection itself to determine + this list, however it is expected that most backends will return + a hardcoded list of values. If the dialect supports "AUTOCOMMIT", + that value should also be present in the sequence returned. + + The method raises ``NotImplementedError`` by default. If a dialect + does not implement this method, then the default dialect will not + perform any checking on a given isolation level value before passing + it onto the :meth:`.Dialect.set_isolation_level` method. This is + to allow backwards-compatibility with third party dialects that may + not yet be implementing this method. + + .. versionadded:: 2.0 + + """ + raise NotImplementedError() + + def _assert_and_set_isolation_level( + self, dbapi_conn: DBAPIConnection, level: IsolationLevel + ) -> None: + raise NotImplementedError() + + @classmethod + def get_dialect_cls(cls, url: URL) -> Type[Dialect]: + """Given a URL, return the :class:`.Dialect` that will be used. + + This is a hook that allows an external plugin to provide functionality + around an existing dialect, by allowing the plugin to be loaded + from the url based on an entrypoint, and then the plugin returns + the actual dialect to be used. + + By default this just returns the cls. + + """ + return cls + + @classmethod + def get_async_dialect_cls(cls, url: URL) -> Type[Dialect]: + """Given a URL, return the :class:`.Dialect` that will be used by + an async engine. + + By default this is an alias of :meth:`.Dialect.get_dialect_cls` and + just returns the cls. It may be used if a dialect provides + both a sync and async version under the same name, like the + ``psycopg`` driver. + + .. versionadded:: 2 + + .. seealso:: + + :meth:`.Dialect.get_dialect_cls` + + """ + return cls.get_dialect_cls(url) + + @classmethod + def load_provisioning(cls) -> None: + """set up the provision.py module for this dialect. + + For dialects that include a provision.py module that sets up + provisioning followers, this method should initiate that process. + + A typical implementation would be:: + + @classmethod + def load_provisioning(cls): + __import__("mydialect.provision") + + The default method assumes a module named ``provision.py`` inside + the owning package of the current dialect, based on the ``__module__`` + attribute:: + + @classmethod + def load_provisioning(cls): + package = ".".join(cls.__module__.split(".")[0:-1]) + try: + __import__(package + ".provision") + except ImportError: + pass + + .. versionadded:: 1.3.14 + + """ + + @classmethod + def engine_created(cls, engine: Engine) -> None: + """A convenience hook called before returning the final + :class:`_engine.Engine`. + + If the dialect returned a different class from the + :meth:`.get_dialect_cls` + method, then the hook is called on both classes, first on + the dialect class returned by the :meth:`.get_dialect_cls` method and + then on the class on which the method was called. + + The hook should be used by dialects and/or wrappers to apply special + events to the engine or its components. In particular, it allows + a dialect-wrapping class to apply dialect-level events. + + """ + + def get_driver_connection(self, connection: DBAPIConnection) -> Any: + """Returns the connection object as returned by the external driver + package. + + For normal dialects that use a DBAPI compliant driver this call + will just return the ``connection`` passed as argument. + For dialects that instead adapt a non DBAPI compliant driver, like + when adapting an asyncio driver, this call will return the + connection-like object as returned by the driver. + + .. versionadded:: 1.4.24 + + """ + raise NotImplementedError() + + def set_engine_execution_options( + self, engine: Engine, opts: CoreExecuteOptionsParameter + ) -> None: + """Establish execution options for a given engine. + + This is implemented by :class:`.DefaultDialect` to establish + event hooks for new :class:`.Connection` instances created + by the given :class:`.Engine` which will then invoke the + :meth:`.Dialect.set_connection_execution_options` method for that + connection. + + """ + raise NotImplementedError() + + def set_connection_execution_options( + self, connection: Connection, opts: CoreExecuteOptionsParameter + ) -> None: + """Establish execution options for a given connection. + + This is implemented by :class:`.DefaultDialect` in order to implement + the :paramref:`_engine.Connection.execution_options.isolation_level` + execution option. Dialects can intercept various execution options + which may need to modify state on a particular DBAPI connection. + + .. versionadded:: 1.4 + + """ + raise NotImplementedError() + + def get_dialect_pool_class(self, url: URL) -> Type[Pool]: + """return a Pool class to use for a given URL""" + raise NotImplementedError() + + def validate_identifier(self, ident: str) -> None: + """Validates an identifier name, raising an exception if invalid""" + + +class CreateEnginePlugin: + """A set of hooks intended to augment the construction of an + :class:`_engine.Engine` object based on entrypoint names in a URL. + + The purpose of :class:`_engine.CreateEnginePlugin` is to allow third-party + systems to apply engine, pool and dialect level event listeners without + the need for the target application to be modified; instead, the plugin + names can be added to the database URL. Target applications for + :class:`_engine.CreateEnginePlugin` include: + + * connection and SQL performance tools, e.g. which use events to track + number of checkouts and/or time spent with statements + + * connectivity plugins such as proxies + + A rudimentary :class:`_engine.CreateEnginePlugin` that attaches a logger + to an :class:`_engine.Engine` object might look like:: + + + import logging + + from sqlalchemy.engine import CreateEnginePlugin + from sqlalchemy import event + + + class LogCursorEventsPlugin(CreateEnginePlugin): + def __init__(self, url, kwargs): + # consume the parameter "log_cursor_logging_name" from the + # URL query + logging_name = url.query.get( + "log_cursor_logging_name", "log_cursor" + ) + + self.log = logging.getLogger(logging_name) + + def update_url(self, url): + "update the URL to one that no longer includes our parameters" + return url.difference_update_query(["log_cursor_logging_name"]) + + def engine_created(self, engine): + "attach an event listener after the new Engine is constructed" + event.listen(engine, "before_cursor_execute", self._log_event) + + def _log_event( + self, + conn, + cursor, + statement, + parameters, + context, + executemany, + ): + + self.log.info("Plugin logged cursor event: %s", statement) + + Plugins are registered using entry points in a similar way as that + of dialects:: + + entry_points = { + "sqlalchemy.plugins": [ + "log_cursor_plugin = myapp.plugins:LogCursorEventsPlugin" + ] + } + + A plugin that uses the above names would be invoked from a database + URL as in:: + + from sqlalchemy import create_engine + + engine = create_engine( + "mysql+pymysql://scott:tiger@localhost/test?" + "plugin=log_cursor_plugin&log_cursor_logging_name=mylogger" + ) + + The ``plugin`` URL parameter supports multiple instances, so that a URL + may specify multiple plugins; they are loaded in the order stated + in the URL:: + + engine = create_engine( + "mysql+pymysql://scott:tiger@localhost/test?" + "plugin=plugin_one&plugin=plugin_twp&plugin=plugin_three" + ) + + The plugin names may also be passed directly to :func:`_sa.create_engine` + using the :paramref:`_sa.create_engine.plugins` argument:: + + engine = create_engine( + "mysql+pymysql://scott:tiger@localhost/test", plugins=["myplugin"] + ) + + .. versionadded:: 1.2.3 plugin names can also be specified + to :func:`_sa.create_engine` as a list + + A plugin may consume plugin-specific arguments from the + :class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is + the dictionary of arguments passed to the :func:`_sa.create_engine` + call. "Consuming" these arguments includes that they must be removed + when the plugin initializes, so that the arguments are not passed along + to the :class:`_engine.Dialect` constructor, where they will raise an + :class:`_exc.ArgumentError` because they are not known by the dialect. + + As of version 1.4 of SQLAlchemy, arguments should continue to be consumed + from the ``kwargs`` dictionary directly, by removing the values with a + method such as ``dict.pop``. Arguments from the :class:`_engine.URL` object + should be consumed by implementing the + :meth:`_engine.CreateEnginePlugin.update_url` method, returning a new copy + of the :class:`_engine.URL` with plugin-specific parameters removed:: + + class MyPlugin(CreateEnginePlugin): + def __init__(self, url, kwargs): + self.my_argument_one = url.query["my_argument_one"] + self.my_argument_two = url.query["my_argument_two"] + self.my_argument_three = kwargs.pop("my_argument_three", None) + + def update_url(self, url): + return url.difference_update_query( + ["my_argument_one", "my_argument_two"] + ) + + Arguments like those illustrated above would be consumed from a + :func:`_sa.create_engine` call such as:: + + from sqlalchemy import create_engine + + engine = create_engine( + "mysql+pymysql://scott:tiger@localhost/test?" + "plugin=myplugin&my_argument_one=foo&my_argument_two=bar", + my_argument_three="bat", + ) + + .. versionchanged:: 1.4 + + The :class:`_engine.URL` object is now immutable; a + :class:`_engine.CreateEnginePlugin` that needs to alter the + :class:`_engine.URL` should implement the newly added + :meth:`_engine.CreateEnginePlugin.update_url` method, which + is invoked after the plugin is constructed. + + For migration, construct the plugin in the following way, checking + for the existence of the :meth:`_engine.CreateEnginePlugin.update_url` + method to detect which version is running:: + + class MyPlugin(CreateEnginePlugin): + def __init__(self, url, kwargs): + if hasattr(CreateEnginePlugin, "update_url"): + # detect the 1.4 API + self.my_argument_one = url.query["my_argument_one"] + self.my_argument_two = url.query["my_argument_two"] + else: + # detect the 1.3 and earlier API - mutate the + # URL directly + self.my_argument_one = url.query.pop("my_argument_one") + self.my_argument_two = url.query.pop("my_argument_two") + + self.my_argument_three = kwargs.pop("my_argument_three", None) + + def update_url(self, url): + # this method is only called in the 1.4 version + return url.difference_update_query( + ["my_argument_one", "my_argument_two"] + ) + + .. seealso:: + + :ref:`change_5526` - overview of the :class:`_engine.URL` change which + also includes notes regarding :class:`_engine.CreateEnginePlugin`. + + + When the engine creation process completes and produces the + :class:`_engine.Engine` object, it is again passed to the plugin via the + :meth:`_engine.CreateEnginePlugin.engine_created` hook. In this hook, additional + changes can be made to the engine, most typically involving setup of + events (e.g. those defined in :ref:`core_event_toplevel`). + + """ # noqa: E501 + + def __init__(self, url: URL, kwargs: Dict[str, Any]): + """Construct a new :class:`.CreateEnginePlugin`. + + The plugin object is instantiated individually for each call + to :func:`_sa.create_engine`. A single :class:`_engine. + Engine` will be + passed to the :meth:`.CreateEnginePlugin.engine_created` method + corresponding to this URL. + + :param url: the :class:`_engine.URL` object. The plugin may inspect + the :class:`_engine.URL` for arguments. Arguments used by the + plugin should be removed, by returning an updated :class:`_engine.URL` + from the :meth:`_engine.CreateEnginePlugin.update_url` method. + + .. versionchanged:: 1.4 + + The :class:`_engine.URL` object is now immutable, so a + :class:`_engine.CreateEnginePlugin` that needs to alter the + :class:`_engine.URL` object should implement the + :meth:`_engine.CreateEnginePlugin.update_url` method. + + :param kwargs: The keyword arguments passed to + :func:`_sa.create_engine`. + + """ + self.url = url + + def update_url(self, url: URL) -> URL: + """Update the :class:`_engine.URL`. + + A new :class:`_engine.URL` should be returned. This method is + typically used to consume configuration arguments from the + :class:`_engine.URL` which must be removed, as they will not be + recognized by the dialect. The + :meth:`_engine.URL.difference_update_query` method is available + to remove these arguments. See the docstring at + :class:`_engine.CreateEnginePlugin` for an example. + + + .. versionadded:: 1.4 + + """ + raise NotImplementedError() + + def handle_dialect_kwargs( + self, dialect_cls: Type[Dialect], dialect_args: Dict[str, Any] + ) -> None: + """parse and modify dialect kwargs""" + + def handle_pool_kwargs( + self, pool_cls: Type[Pool], pool_args: Dict[str, Any] + ) -> None: + """parse and modify pool kwargs""" + + def engine_created(self, engine: Engine) -> None: + """Receive the :class:`_engine.Engine` + object when it is fully constructed. + + The plugin may make additional changes to the engine, such as + registering engine or connection pool events. + + """ + + +class ExecutionContext: + """A messenger object for a Dialect that corresponds to a single + execution. + + """ + + engine: Engine + """engine which the Connection is associated with""" + + connection: Connection + """Connection object which can be freely used by default value + generators to execute SQL. This Connection should reference the + same underlying connection/transactional resources of + root_connection.""" + + root_connection: Connection + """Connection object which is the source of this ExecutionContext.""" + + dialect: Dialect + """dialect which created this ExecutionContext.""" + + cursor: DBAPICursor + """DB-API cursor procured from the connection""" + + compiled: Optional[Compiled] + """if passed to constructor, sqlalchemy.engine.base.Compiled object + being executed""" + + statement: str + """string version of the statement to be executed. Is either + passed to the constructor, or must be created from the + sql.Compiled object by the time pre_exec() has completed.""" + + invoked_statement: Optional[Executable] + """The Executable statement object that was given in the first place. + + This should be structurally equivalent to compiled.statement, but not + necessarily the same object as in a caching scenario the compiled form + will have been extracted from the cache. + + """ + + parameters: _AnyMultiExecuteParams + """bind parameters passed to the execute() or exec_driver_sql() methods. + + These are always stored as a list of parameter entries. A single-element + list corresponds to a ``cursor.execute()`` call and a multiple-element + list corresponds to ``cursor.executemany()``, except in the case + of :attr:`.ExecuteStyle.INSERTMANYVALUES` which will use + ``cursor.execute()`` one or more times. + + """ + + no_parameters: bool + """True if the execution style does not use parameters""" + + isinsert: bool + """True if the statement is an INSERT.""" + + isupdate: bool + """True if the statement is an UPDATE.""" + + execute_style: ExecuteStyle + """the style of DBAPI cursor method that will be used to execute + a statement. + + .. versionadded:: 2.0 + + """ + + executemany: bool + """True if the context has a list of more than one parameter set. + + Historically this attribute links to whether ``cursor.execute()`` or + ``cursor.executemany()`` will be used. It also can now mean that + "insertmanyvalues" may be used which indicates one or more + ``cursor.execute()`` calls. + + """ + + prefetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]] + """a list of Column objects for which a client-side default + was fired off. Applies to inserts and updates.""" + + postfetch_cols: util.generic_fn_descriptor[Optional[Sequence[Column[Any]]]] + """a list of Column objects for which a server-side default or + inline SQL expression value was fired off. Applies to inserts + and updates.""" + + execution_options: _ExecuteOptions + """Execution options associated with the current statement execution""" + + @classmethod + def _init_ddl( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + compiled_ddl: DDLCompiler, + ) -> ExecutionContext: + raise NotImplementedError() + + @classmethod + def _init_compiled( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + compiled: SQLCompiler, + parameters: _CoreMultiExecuteParams, + invoked_statement: Executable, + extracted_parameters: Optional[Sequence[BindParameter[Any]]], + cache_hit: CacheStats = CacheStats.CACHING_DISABLED, + ) -> ExecutionContext: + raise NotImplementedError() + + @classmethod + def _init_statement( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + statement: str, + parameters: _DBAPIMultiExecuteParams, + ) -> ExecutionContext: + raise NotImplementedError() + + @classmethod + def _init_default( + cls, + dialect: Dialect, + connection: Connection, + dbapi_connection: PoolProxiedConnection, + execution_options: _ExecuteOptions, + ) -> ExecutionContext: + raise NotImplementedError() + + def _exec_default( + self, + column: Optional[Column[Any]], + default: DefaultGenerator, + type_: Optional[TypeEngine[Any]], + ) -> Any: + raise NotImplementedError() + + def _prepare_set_input_sizes( + self, + ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]: + raise NotImplementedError() + + def _get_cache_stats(self) -> str: + raise NotImplementedError() + + def _setup_result_proxy(self) -> CursorResult[Any]: + raise NotImplementedError() + + def fire_sequence(self, seq: Sequence_SchemaItem, type_: Integer) -> int: + """given a :class:`.Sequence`, invoke it and return the next int + value""" + raise NotImplementedError() + + def create_cursor(self) -> DBAPICursor: + """Return a new cursor generated from this ExecutionContext's + connection. + + Some dialects may wish to change the behavior of + connection.cursor(), such as postgresql which may return a PG + "server side" cursor. + """ + + raise NotImplementedError() + + def pre_exec(self) -> None: + """Called before an execution of a compiled statement. + + If a compiled statement was passed to this ExecutionContext, + the `statement` and `parameters` datamembers must be + initialized after this statement is complete. + """ + + raise NotImplementedError() + + def get_out_parameter_values( + self, out_param_names: Sequence[str] + ) -> Sequence[Any]: + """Return a sequence of OUT parameter values from a cursor. + + For dialects that support OUT parameters, this method will be called + when there is a :class:`.SQLCompiler` object which has the + :attr:`.SQLCompiler.has_out_parameters` flag set. This flag in turn + will be set to True if the statement itself has :class:`.BindParameter` + objects that have the ``.isoutparam`` flag set which are consumed by + the :meth:`.SQLCompiler.visit_bindparam` method. If the dialect + compiler produces :class:`.BindParameter` objects with ``.isoutparam`` + set which are not handled by :meth:`.SQLCompiler.visit_bindparam`, it + should set this flag explicitly. + + The list of names that were rendered for each bound parameter + is passed to the method. The method should then return a sequence of + values corresponding to the list of parameter objects. Unlike in + previous SQLAlchemy versions, the values can be the **raw values** from + the DBAPI; the execution context will apply the appropriate type + handler based on what's present in self.compiled.binds and update the + values. The processed dictionary will then be made available via the + ``.out_parameters`` collection on the result object. Note that + SQLAlchemy 1.4 has multiple kinds of result object as part of the 2.0 + transition. + + .. versionadded:: 1.4 - added + :meth:`.ExecutionContext.get_out_parameter_values`, which is invoked + automatically by the :class:`.DefaultExecutionContext` when there + are :class:`.BindParameter` objects with the ``.isoutparam`` flag + set. This replaces the practice of setting out parameters within + the now-removed ``get_result_proxy()`` method. + + """ + raise NotImplementedError() + + def post_exec(self) -> None: + """Called after the execution of a compiled statement. + + If a compiled statement was passed to this ExecutionContext, + the `last_insert_ids`, `last_inserted_params`, etc. + datamembers should be available after this method completes. + """ + + raise NotImplementedError() + + def handle_dbapi_exception(self, e: BaseException) -> None: + """Receive a DBAPI exception which occurred upon execute, result + fetch, etc.""" + + raise NotImplementedError() + + def lastrow_has_defaults(self) -> bool: + """Return True if the last INSERT or UPDATE row contained + inlined or database-side defaults. + """ + + raise NotImplementedError() + + def get_rowcount(self) -> Optional[int]: + """Return the DBAPI ``cursor.rowcount`` value, or in some + cases an interpreted value. + + See :attr:`_engine.CursorResult.rowcount` for details on this. + + """ + + raise NotImplementedError() + + def fetchall_for_returning(self, cursor: DBAPICursor) -> Sequence[Any]: + """For a RETURNING result, deliver cursor.fetchall() from the + DBAPI cursor. + + This is a dialect-specific hook for dialects that have special + considerations when calling upon the rows delivered for a + "RETURNING" statement. Default implementation is + ``cursor.fetchall()``. + + This hook is currently used only by the :term:`insertmanyvalues` + feature. Dialects that don't set ``use_insertmanyvalues=True`` + don't need to consider this hook. + + .. versionadded:: 2.0.10 + + """ + raise NotImplementedError() + + +class ConnectionEventsTarget(EventTarget): + """An object which can accept events from :class:`.ConnectionEvents`. + + Includes :class:`_engine.Connection` and :class:`_engine.Engine`. + + .. versionadded:: 2.0 + + """ + + dispatch: dispatcher[ConnectionEventsTarget] + + +Connectable = ConnectionEventsTarget + + +class ExceptionContext: + """Encapsulate information about an error condition in progress. + + This object exists solely to be passed to the + :meth:`_events.DialectEvents.handle_error` event, + supporting an interface that + can be extended without backwards-incompatibility. + + + """ + + __slots__ = () + + dialect: Dialect + """The :class:`_engine.Dialect` in use. + + This member is present for all invocations of the event hook. + + .. versionadded:: 2.0 + + """ + + connection: Optional[Connection] + """The :class:`_engine.Connection` in use during the exception. + + This member is present, except in the case of a failure when + first connecting. + + .. seealso:: + + :attr:`.ExceptionContext.engine` + + + """ + + engine: Optional[Engine] + """The :class:`_engine.Engine` in use during the exception. + + This member is present in all cases except for when handling an error + within the connection pool "pre-ping" process. + + """ + + cursor: Optional[DBAPICursor] + """The DBAPI cursor object. + + May be None. + + """ + + statement: Optional[str] + """String SQL statement that was emitted directly to the DBAPI. + + May be None. + + """ + + parameters: Optional[_DBAPIAnyExecuteParams] + """Parameter collection that was emitted directly to the DBAPI. + + May be None. + + """ + + original_exception: BaseException + """The exception object which was caught. + + This member is always present. + + """ + + sqlalchemy_exception: Optional[StatementError] + """The :class:`sqlalchemy.exc.StatementError` which wraps the original, + and will be raised if exception handling is not circumvented by the event. + + May be None, as not all exception types are wrapped by SQLAlchemy. + For DBAPI-level exceptions that subclass the dbapi's Error class, this + field will always be present. + + """ + + chained_exception: Optional[BaseException] + """The exception that was returned by the previous handler in the + exception chain, if any. + + If present, this exception will be the one ultimately raised by + SQLAlchemy unless a subsequent handler replaces it. + + May be None. + + """ + + execution_context: Optional[ExecutionContext] + """The :class:`.ExecutionContext` corresponding to the execution + operation in progress. + + This is present for statement execution operations, but not for + operations such as transaction begin/end. It also is not present when + the exception was raised before the :class:`.ExecutionContext` + could be constructed. + + Note that the :attr:`.ExceptionContext.statement` and + :attr:`.ExceptionContext.parameters` members may represent a + different value than that of the :class:`.ExecutionContext`, + potentially in the case where a + :meth:`_events.ConnectionEvents.before_cursor_execute` event or similar + modified the statement/parameters to be sent. + + May be None. + + """ + + is_disconnect: bool + """Represent whether the exception as occurred represents a "disconnect" + condition. + + This flag will always be True or False within the scope of the + :meth:`_events.DialectEvents.handle_error` handler. + + SQLAlchemy will defer to this flag in order to determine whether or not + the connection should be invalidated subsequently. That is, by + assigning to this flag, a "disconnect" event which then results in + a connection and pool invalidation can be invoked or prevented by + changing this flag. + + + .. note:: The pool "pre_ping" handler enabled using the + :paramref:`_sa.create_engine.pool_pre_ping` parameter does **not** + consult this event before deciding if the "ping" returned false, + as opposed to receiving an unhandled error. For this use case, the + :ref:`legacy recipe based on engine_connect() may be used + `. A future API allow more + comprehensive customization of the "disconnect" detection mechanism + across all functions. + + """ + + invalidate_pool_on_disconnect: bool + """Represent whether all connections in the pool should be invalidated + when a "disconnect" condition is in effect. + + Setting this flag to False within the scope of the + :meth:`_events.DialectEvents.handle_error` + event will have the effect such + that the full collection of connections in the pool will not be + invalidated during a disconnect; only the current connection that is the + subject of the error will actually be invalidated. + + The purpose of this flag is for custom disconnect-handling schemes where + the invalidation of other connections in the pool is to be performed + based on other conditions, or even on a per-connection basis. + + """ + + is_pre_ping: bool + """Indicates if this error is occurring within the "pre-ping" step + performed when :paramref:`_sa.create_engine.pool_pre_ping` is set to + ``True``. In this mode, the :attr:`.ExceptionContext.engine` attribute + will be ``None``. The dialect in use is accessible via the + :attr:`.ExceptionContext.dialect` attribute. + + .. versionadded:: 2.0.5 + + """ + + +class AdaptedConnection: + """Interface of an adapted connection object to support the DBAPI protocol. + + Used by asyncio dialects to provide a sync-style pep-249 facade on top + of the asyncio connection/cursor API provided by the driver. + + .. versionadded:: 1.4.24 + + """ + + __slots__ = ("_connection",) + + _connection: AsyncIODBAPIConnection + + @property + def driver_connection(self) -> Any: + """The connection object as returned by the driver after a connect.""" + return self._connection + + def run_async(self, fn: Callable[[Any], Awaitable[_T]]) -> _T: + """Run the awaitable returned by the given function, which is passed + the raw asyncio driver connection. + + This is used to invoke awaitable-only methods on the driver connection + within the context of a "synchronous" method, like a connection + pool event handler. + + E.g.:: + + engine = create_async_engine(...) + + + @event.listens_for(engine.sync_engine, "connect") + def register_custom_types( + dbapi_connection, # ... + ): + dbapi_connection.run_async( + lambda connection: connection.set_type_codec( + "MyCustomType", encoder, decoder, ... + ) + ) + + .. versionadded:: 1.4.30 + + .. seealso:: + + :ref:`asyncio_events_run_async` + + """ + return await_only(fn(self._connection)) + + def __repr__(self) -> str: + return "" % self._connection diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/mock.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..7d21c876cbd6e13e2088423f643ce29d5ac09616 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/mock.py @@ -0,0 +1,134 @@ +# engine/mock.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +from operator import attrgetter +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Optional +from typing import Type +from typing import Union + +from . import url as _url +from .. import util + + +if typing.TYPE_CHECKING: + from .base import Engine + from .interfaces import _CoreAnyExecuteParams + from .interfaces import CoreExecuteOptionsParameter + from .interfaces import Dialect + from .url import URL + from ..sql.base import Executable + from ..sql.ddl import InvokeDDLBase + from ..sql.schema import HasSchemaAttr + from ..sql.visitors import Visitable + + +class MockConnection: + def __init__(self, dialect: Dialect, execute: Callable[..., Any]): + self._dialect = dialect + self._execute_impl = execute + + engine: Engine = cast(Any, property(lambda s: s)) + dialect: Dialect = cast(Any, property(attrgetter("_dialect"))) + name: str = cast(Any, property(lambda s: s._dialect.name)) + + def connect(self, **kwargs: Any) -> MockConnection: + return self + + def schema_for_object(self, obj: HasSchemaAttr) -> Optional[str]: + return obj.schema + + def execution_options(self, **kw: Any) -> MockConnection: + return self + + def _run_ddl_visitor( + self, + visitorcallable: Type[InvokeDDLBase], + element: Visitable, + **kwargs: Any, + ) -> None: + kwargs["checkfirst"] = False + visitorcallable( + dialect=self.dialect, connection=self, **kwargs + ).traverse_single(element) + + def execute( + self, + obj: Executable, + parameters: Optional[_CoreAnyExecuteParams] = None, + execution_options: Optional[CoreExecuteOptionsParameter] = None, + ) -> Any: + return self._execute_impl(obj, parameters) + + +def create_mock_engine( + url: Union[str, URL], executor: Any, **kw: Any +) -> MockConnection: + """Create a "mock" engine used for echoing DDL. + + This is a utility function used for debugging or storing the output of DDL + sequences as generated by :meth:`_schema.MetaData.create_all` + and related methods. + + The function accepts a URL which is used only to determine the kind of + dialect to be used, as well as an "executor" callable function which + will receive a SQL expression object and parameters, which can then be + echoed or otherwise printed. The executor's return value is not handled, + nor does the engine allow regular string statements to be invoked, and + is therefore only useful for DDL that is sent to the database without + receiving any results. + + E.g.:: + + from sqlalchemy import create_mock_engine + + + def dump(sql, *multiparams, **params): + print(sql.compile(dialect=engine.dialect)) + + + engine = create_mock_engine("postgresql+psycopg2://", dump) + metadata.create_all(engine, checkfirst=False) + + :param url: A string URL which typically needs to contain only the + database backend name. + + :param executor: a callable which receives the arguments ``sql``, + ``*multiparams`` and ``**params``. The ``sql`` parameter is typically + an instance of :class:`.ExecutableDDLElement`, which can then be compiled + into a string using :meth:`.ExecutableDDLElement.compile`. + + .. versionadded:: 1.4 - the :func:`.create_mock_engine` function replaces + the previous "mock" engine strategy used with + :func:`_sa.create_engine`. + + .. seealso:: + + :ref:`faq_ddl_as_string` + + """ + + # create url.URL object + u = _url.make_url(url) + + dialect_cls = u.get_dialect() + + dialect_args = {} + # consume dialect arguments from kwargs + for k in util.get_cls_kwargs(dialect_cls): + if k in kw: + dialect_args[k] = kw.pop(k) + + # create dialect + dialect = dialect_cls(**dialect_args) + + return MockConnection(dialect, executor) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/processors.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/processors.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5f78145631d163c3db3eda5c5d33c3acec5d96 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/processors.py @@ -0,0 +1,61 @@ +# engine/processors.py +# Copyright (C) 2010-2026 the SQLAlchemy authors and contributors +# +# Copyright (C) 2010 Gaetan de Menten gdementen@gmail.com +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""defines generic type conversion functions, as used in bind and result +processors. + +They all share one common characteristic: None is passed through unchanged. + +""" +from __future__ import annotations + +import typing + +from ._py_processors import str_to_datetime_processor_factory # noqa +from ..util._has_cy import HAS_CYEXTENSION + +if typing.TYPE_CHECKING or not HAS_CYEXTENSION: + from ._py_processors import int_to_boolean as int_to_boolean + from ._py_processors import str_to_date as str_to_date + from ._py_processors import str_to_datetime as str_to_datetime + from ._py_processors import str_to_time as str_to_time + from ._py_processors import ( + to_decimal_processor_factory as to_decimal_processor_factory, + ) + from ._py_processors import to_float as to_float + from ._py_processors import to_str as to_str +else: + from sqlalchemy.cyextension.processors import ( + DecimalResultProcessor, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401 + int_to_boolean as int_to_boolean, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401,E501 + str_to_date as str_to_date, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401 + str_to_datetime as str_to_datetime, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401,E501 + str_to_time as str_to_time, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401,E501 + to_float as to_float, + ) + from sqlalchemy.cyextension.processors import ( # noqa: F401,E501 + to_str as to_str, + ) + + def to_decimal_processor_factory(target_class, scale): + # Note that the scale argument is not taken into account for integer + # values in the C implementation while it is in the Python one. + # For example, the Python implementation might return + # Decimal('5.00000') whereas the C implementation will + # return Decimal('5'). These are equivalent of course. + return DecimalResultProcessor(target_class, "%%.%df" % scale).process diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/reflection.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..02900ee39eddbee7c4547be464f5484d461b40e1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/reflection.py @@ -0,0 +1,2102 @@ +# engine/reflection.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Provides an abstraction for obtaining database schema information. + +Usage Notes: + +Here are some general conventions when accessing the low level inspector +methods such as get_table_names, get_columns, etc. + +1. Inspector methods return lists of dicts in most cases for the following + reasons: + + * They're both standard types that can be serialized. + * Using a dict instead of a tuple allows easy expansion of attributes. + * Using a list for the outer structure maintains order and is easy to work + with (e.g. list comprehension [d['name'] for d in cols]). + +2. Records that contain a name, such as the column name in a column record + use the key 'name'. So for most return values, each record will have a + 'name' attribute.. +""" +from __future__ import annotations + +import contextlib +from dataclasses import dataclass +from enum import auto +from enum import Flag +from enum import unique +from typing import Any +from typing import Callable +from typing import Collection +from typing import Dict +from typing import Generator +from typing import Iterable +from typing import List +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .base import Connection +from .base import Engine +from .. import exc +from .. import inspection +from .. import sql +from .. import util +from ..sql import operators +from ..sql import schema as sa_schema +from ..sql.cache_key import _ad_hoc_cache_key_from_args +from ..sql.elements import quoted_name +from ..sql.elements import TextClause +from ..sql.type_api import TypeEngine +from ..sql.visitors import InternalTraversal +from ..util import topological +from ..util.typing import final + +if TYPE_CHECKING: + from .interfaces import Dialect + from .interfaces import ReflectedCheckConstraint + from .interfaces import ReflectedColumn + from .interfaces import ReflectedForeignKeyConstraint + from .interfaces import ReflectedIndex + from .interfaces import ReflectedPrimaryKeyConstraint + from .interfaces import ReflectedTableComment + from .interfaces import ReflectedUniqueConstraint + from .interfaces import TableKey + +_R = TypeVar("_R") + + +@util.decorator +def cache( + fn: Callable[..., _R], + self: Dialect, + con: Connection, + *args: Any, + **kw: Any, +) -> _R: + info_cache = kw.get("info_cache", None) + if info_cache is None: + return fn(self, con, *args, **kw) + exclude = {"info_cache", "unreflectable"} + key = ( + fn.__name__, + tuple( + (str(a), a.quote) if isinstance(a, quoted_name) else a + for a in args + if isinstance(a, str) + ), + tuple( + (k, (str(v), v.quote) if isinstance(v, quoted_name) else v) + for k, v in kw.items() + if k not in exclude + ), + ) + ret: _R = info_cache.get(key) + if ret is None: + ret = fn(self, con, *args, **kw) + info_cache[key] = ret + return ret + + +def flexi_cache( + *traverse_args: Tuple[str, InternalTraversal] +) -> Callable[[Callable[..., _R]], Callable[..., _R]]: + @util.decorator + def go( + fn: Callable[..., _R], + self: Dialect, + con: Connection, + *args: Any, + **kw: Any, + ) -> _R: + info_cache = kw.get("info_cache", None) + if info_cache is None: + return fn(self, con, *args, **kw) + key = _ad_hoc_cache_key_from_args((fn.__name__,), traverse_args, args) + ret: _R = info_cache.get(key) + if ret is None: + ret = fn(self, con, *args, **kw) + info_cache[key] = ret + return ret + + return go + + +@unique +class ObjectKind(Flag): + """Enumerator that indicates which kind of object to return when calling + the ``get_multi`` methods. + + This is a Flag enum, so custom combinations can be passed. For example, + to reflect tables and plain views ``ObjectKind.TABLE | ObjectKind.VIEW`` + may be used. + + .. note:: + Not all dialect may support all kind of object. If a dialect does + not support a particular object an empty dict is returned. + In case a dialect supports an object, but the requested method + is not applicable for the specified kind the default value + will be returned for each reflected object. For example reflecting + check constraints of view return a dict with all the views with + empty lists as values. + """ + + TABLE = auto() + "Reflect table objects" + VIEW = auto() + "Reflect plain view objects" + MATERIALIZED_VIEW = auto() + "Reflect materialized view object" + + ANY_VIEW = VIEW | MATERIALIZED_VIEW + "Reflect any kind of view objects" + ANY = TABLE | VIEW | MATERIALIZED_VIEW + "Reflect all type of objects" + + +@unique +class ObjectScope(Flag): + """Enumerator that indicates which scope to use when calling + the ``get_multi`` methods. + """ + + DEFAULT = auto() + "Include default scope" + TEMPORARY = auto() + "Include only temp scope" + ANY = DEFAULT | TEMPORARY + "Include both default and temp scope" + + +@inspection._self_inspects +class Inspector(inspection.Inspectable["Inspector"]): + """Performs database schema inspection. + + The Inspector acts as a proxy to the reflection methods of the + :class:`~sqlalchemy.engine.interfaces.Dialect`, providing a + consistent interface as well as caching support for previously + fetched metadata. + + A :class:`_reflection.Inspector` object is usually created via the + :func:`_sa.inspect` function, which may be passed an + :class:`_engine.Engine` + or a :class:`_engine.Connection`:: + + from sqlalchemy import inspect, create_engine + + engine = create_engine("...") + insp = inspect(engine) + + Where above, the :class:`~sqlalchemy.engine.interfaces.Dialect` associated + with the engine may opt to return an :class:`_reflection.Inspector` + subclass that + provides additional methods specific to the dialect's target database. + + """ + + bind: Union[Engine, Connection] + engine: Engine + _op_context_requires_connect: bool + dialect: Dialect + info_cache: Dict[Any, Any] + + @util.deprecated( + "1.4", + "The __init__() method on :class:`_reflection.Inspector` " + "is deprecated and " + "will be removed in a future release. Please use the " + ":func:`.sqlalchemy.inspect` " + "function on an :class:`_engine.Engine` or " + ":class:`_engine.Connection` " + "in order to " + "acquire an :class:`_reflection.Inspector`.", + ) + def __init__(self, bind: Union[Engine, Connection]): + """Initialize a new :class:`_reflection.Inspector`. + + :param bind: a :class:`~sqlalchemy.engine.Connection`, + which is typically an instance of + :class:`~sqlalchemy.engine.Engine` or + :class:`~sqlalchemy.engine.Connection`. + + For a dialect-specific instance of :class:`_reflection.Inspector`, see + :meth:`_reflection.Inspector.from_engine` + + """ + self._init_legacy(bind) + + @classmethod + def _construct( + cls, init: Callable[..., Any], bind: Union[Engine, Connection] + ) -> Inspector: + if hasattr(bind.dialect, "inspector"): + cls = bind.dialect.inspector + + self = cls.__new__(cls) + init(self, bind) + return self + + def _init_legacy(self, bind: Union[Engine, Connection]) -> None: + if hasattr(bind, "exec_driver_sql"): + self._init_connection(bind) # type: ignore[arg-type] + else: + self._init_engine(bind) + + def _init_engine(self, engine: Engine) -> None: + self.bind = self.engine = engine + engine.connect().close() + self._op_context_requires_connect = True + self.dialect = self.engine.dialect + self.info_cache = {} + + def _init_connection(self, connection: Connection) -> None: + self.bind = connection + self.engine = connection.engine + self._op_context_requires_connect = False + self.dialect = self.engine.dialect + self.info_cache = {} + + def clear_cache(self) -> None: + """reset the cache for this :class:`.Inspector`. + + Inspection methods that have data cached will emit SQL queries + when next called to get new data. + + .. versionadded:: 2.0 + + """ + self.info_cache.clear() + + @classmethod + @util.deprecated( + "1.4", + "The from_engine() method on :class:`_reflection.Inspector` " + "is deprecated and " + "will be removed in a future release. Please use the " + ":func:`.sqlalchemy.inspect` " + "function on an :class:`_engine.Engine` or " + ":class:`_engine.Connection` " + "in order to " + "acquire an :class:`_reflection.Inspector`.", + ) + def from_engine(cls, bind: Engine) -> Inspector: + """Construct a new dialect-specific Inspector object from the given + engine or connection. + + :param bind: a :class:`~sqlalchemy.engine.Connection` + or :class:`~sqlalchemy.engine.Engine`. + + This method differs from direct a direct constructor call of + :class:`_reflection.Inspector` in that the + :class:`~sqlalchemy.engine.interfaces.Dialect` is given a chance to + provide a dialect-specific :class:`_reflection.Inspector` instance, + which may + provide additional methods. + + See the example at :class:`_reflection.Inspector`. + + """ + return cls._construct(cls._init_legacy, bind) + + @inspection._inspects(Engine) + def _engine_insp(bind: Engine) -> Inspector: # type: ignore[misc] + return Inspector._construct(Inspector._init_engine, bind) + + @inspection._inspects(Connection) + def _connection_insp(bind: Connection) -> Inspector: # type: ignore[misc] + return Inspector._construct(Inspector._init_connection, bind) + + @contextlib.contextmanager + def _operation_context(self) -> Generator[Connection, None, None]: + """Return a context that optimizes for multiple operations on a single + transaction. + + This essentially allows connect()/close() to be called if we detected + that we're against an :class:`_engine.Engine` and not a + :class:`_engine.Connection`. + + """ + conn: Connection + if self._op_context_requires_connect: + conn = self.bind.connect() # type: ignore[union-attr] + else: + conn = self.bind # type: ignore[assignment] + try: + yield conn + finally: + if self._op_context_requires_connect: + conn.close() + + @contextlib.contextmanager + def _inspection_context(self) -> Generator[Inspector, None, None]: + """Return an :class:`_reflection.Inspector` + from this one that will run all + operations on a single connection. + + """ + + with self._operation_context() as conn: + sub_insp = self._construct(self.__class__._init_connection, conn) + sub_insp.info_cache = self.info_cache + yield sub_insp + + @property + def default_schema_name(self) -> Optional[str]: + """Return the default schema name presented by the dialect + for the current engine's database user. + + E.g. this is typically ``public`` for PostgreSQL and ``dbo`` + for SQL Server. + + """ + return self.dialect.default_schema_name + + def get_schema_names(self, **kw: Any) -> List[str]: + r"""Return all schema names. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + """ + + with self._operation_context() as conn: + return self.dialect.get_schema_names( + conn, info_cache=self.info_cache, **kw + ) + + def get_table_names( + self, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + r"""Return all table names within a particular schema. + + The names are expected to be real tables only, not views. + Views are instead returned using the + :meth:`_reflection.Inspector.get_view_names` and/or + :meth:`_reflection.Inspector.get_materialized_view_names` + methods. + + :param schema: Schema name. If ``schema`` is left at ``None``, the + database's default schema is + used, else the named schema is searched. If the database does not + support named schemas, behavior is undefined if ``schema`` is not + passed as ``None``. For special quoting, use :class:`.quoted_name`. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. seealso:: + + :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names` + + :attr:`_schema.MetaData.sorted_tables` + + """ + + with self._operation_context() as conn: + return self.dialect.get_table_names( + conn, schema, info_cache=self.info_cache, **kw + ) + + def has_table( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> bool: + r"""Return True if the backend has a table, view, or temporary + table of the given name. + + :param table_name: name of the table to check + :param schema: schema name to query, if not the default schema. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. versionadded:: 1.4 - the :meth:`.Inspector.has_table` method + replaces the :meth:`_engine.Engine.has_table` method. + + .. versionchanged:: 2.0:: :meth:`.Inspector.has_table` now formally + supports checking for additional table-like objects: + + * any type of views (plain or materialized) + * temporary tables of any kind + + Previously, these two checks were not formally specified and + different dialects would vary in their behavior. The dialect + testing suite now includes tests for all of these object types + and should be supported by all SQLAlchemy-included dialects. + Support among third party dialects may be lagging, however. + + """ + with self._operation_context() as conn: + return self.dialect.has_table( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def has_sequence( + self, sequence_name: str, schema: Optional[str] = None, **kw: Any + ) -> bool: + r"""Return True if the backend has a sequence with the given name. + + :param sequence_name: name of the sequence to check + :param schema: schema name to query, if not the default schema. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. versionadded:: 1.4 + + """ + with self._operation_context() as conn: + return self.dialect.has_sequence( + conn, sequence_name, schema, info_cache=self.info_cache, **kw + ) + + def has_index( + self, + table_name: str, + index_name: str, + schema: Optional[str] = None, + **kw: Any, + ) -> bool: + r"""Check the existence of a particular index name in the database. + + :param table_name: the name of the table the index belongs to + :param index_name: the name of the index to check + :param schema: schema name to query, if not the default schema. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. versionadded:: 2.0 + + """ + with self._operation_context() as conn: + return self.dialect.has_index( + conn, + table_name, + index_name, + schema, + info_cache=self.info_cache, + **kw, + ) + + def has_schema(self, schema_name: str, **kw: Any) -> bool: + r"""Return True if the backend has a schema with the given name. + + :param schema_name: name of the schema to check + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. versionadded:: 2.0 + + """ + with self._operation_context() as conn: + return self.dialect.has_schema( + conn, schema_name, info_cache=self.info_cache, **kw + ) + + def get_sorted_table_and_fkc_names( + self, + schema: Optional[str] = None, + **kw: Any, + ) -> List[Tuple[Optional[str], List[Tuple[str, Optional[str]]]]]: + r"""Return dependency-sorted table and foreign key constraint names in + referred to within a particular schema. + + This will yield 2-tuples of + ``(tablename, [(tname, fkname), (tname, fkname), ...])`` + consisting of table names in CREATE order grouped with the foreign key + constraint names that are not detected as belonging to a cycle. + The final element + will be ``(None, [(tname, fkname), (tname, fkname), ..])`` + which will consist of remaining + foreign key constraint names that would require a separate CREATE + step after-the-fact, based on dependencies between tables. + + :param schema: schema name to query, if not the default schema. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. seealso:: + + :meth:`_reflection.Inspector.get_table_names` + + :func:`.sort_tables_and_constraints` - similar method which works + with an already-given :class:`_schema.MetaData`. + + """ + + return [ + ( + table_key[1] if table_key else None, + [(tname, fks) for (_, tname), fks in fk_collection], + ) + for ( + table_key, + fk_collection, + ) in self.sort_tables_on_foreign_key_dependency( + consider_schemas=(schema,) + ) + ] + + def sort_tables_on_foreign_key_dependency( + self, + consider_schemas: Collection[Optional[str]] = (None,), + **kw: Any, + ) -> List[ + Tuple[ + Optional[Tuple[Optional[str], str]], + List[Tuple[Tuple[Optional[str], str], Optional[str]]], + ] + ]: + r"""Return dependency-sorted table and foreign key constraint names + referred to within multiple schemas. + + This method may be compared to + :meth:`.Inspector.get_sorted_table_and_fkc_names`, which + works on one schema at a time; here, the method is a generalization + that will consider multiple schemas at once including that it will + resolve for cross-schema foreign keys. + + .. versionadded:: 2.0 + + """ + SchemaTab = Tuple[Optional[str], str] + + tuples: Set[Tuple[SchemaTab, SchemaTab]] = set() + remaining_fkcs: Set[Tuple[SchemaTab, Optional[str]]] = set() + fknames_for_table: Dict[SchemaTab, Set[Optional[str]]] = {} + tnames: List[SchemaTab] = [] + + for schname in consider_schemas: + schema_fkeys = self.get_multi_foreign_keys(schname, **kw) + tnames.extend(schema_fkeys) + for (_, tname), fkeys in schema_fkeys.items(): + fknames_for_table[(schname, tname)] = { + fk["name"] for fk in fkeys + } + for fkey in fkeys: + if ( + tname != fkey["referred_table"] + or schname != fkey["referred_schema"] + ): + tuples.add( + ( + ( + fkey["referred_schema"], + fkey["referred_table"], + ), + (schname, tname), + ) + ) + try: + candidate_sort = list(topological.sort(tuples, tnames)) + except exc.CircularDependencyError as err: + edge: Tuple[SchemaTab, SchemaTab] + for edge in err.edges: + tuples.remove(edge) + remaining_fkcs.update( + (edge[1], fkc) for fkc in fknames_for_table[edge[1]] + ) + + candidate_sort = list(topological.sort(tuples, tnames)) + ret: List[ + Tuple[Optional[SchemaTab], List[Tuple[SchemaTab, Optional[str]]]] + ] + ret = [ + ( + (schname, tname), + [ + ((schname, tname), fk) + for fk in fknames_for_table[(schname, tname)].difference( + name for _, name in remaining_fkcs + ) + ], + ) + for (schname, tname) in candidate_sort + ] + return ret + [(None, list(remaining_fkcs))] + + def get_temp_table_names(self, **kw: Any) -> List[str]: + r"""Return a list of temporary table names for the current bind. + + This method is unsupported by most dialects; currently + only Oracle Database, PostgreSQL and SQLite implements it. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + """ + + with self._operation_context() as conn: + return self.dialect.get_temp_table_names( + conn, info_cache=self.info_cache, **kw + ) + + def get_temp_view_names(self, **kw: Any) -> List[str]: + r"""Return a list of temporary view names for the current bind. + + This method is unsupported by most dialects; currently + only PostgreSQL and SQLite implements it. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + """ + with self._operation_context() as conn: + return self.dialect.get_temp_view_names( + conn, info_cache=self.info_cache, **kw + ) + + def get_table_options( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> Dict[str, Any]: + r"""Return a dictionary of options specified when the table of the + given name was created. + + This currently includes some options that apply to MySQL and Oracle + Database tables. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dict with the table options. The returned keys depend on the + dialect in use. Each one is prefixed with the dialect name. + + .. seealso:: :meth:`Inspector.get_multi_table_options` + + """ + with self._operation_context() as conn: + return self.dialect.get_table_options( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_table_options( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, Dict[str, Any]]: + r"""Return a dictionary of options specified when the tables in the + given schema were created. + + The tables can be filtered by passing the names to use to + ``filter_names``. + + This currently includes some options that apply to MySQL and Oracle + tables. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if options of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are dictionaries with the table options. + The returned keys in each dict depend on the + dialect in use. Each one is prefixed with the dialect name. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_table_options` + """ + with self._operation_context() as conn: + res = self.dialect.get_multi_table_options( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + return dict(res) + + def get_view_names( + self, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + r"""Return all non-materialized view names in `schema`. + + :param schema: Optional, retrieve names from a non-default schema. + For special quoting, use :class:`.quoted_name`. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + + .. versionchanged:: 2.0 For those dialects that previously included + the names of materialized views in this list (currently PostgreSQL), + this method no longer returns the names of materialized views. + the :meth:`.Inspector.get_materialized_view_names` method should + be used instead. + + .. seealso:: + + :meth:`.Inspector.get_materialized_view_names` + + """ + + with self._operation_context() as conn: + return self.dialect.get_view_names( + conn, schema, info_cache=self.info_cache, **kw + ) + + def get_materialized_view_names( + self, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + r"""Return all materialized view names in `schema`. + + :param schema: Optional, retrieve names from a non-default schema. + For special quoting, use :class:`.quoted_name`. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + .. versionadded:: 2.0 + + .. seealso:: + + :meth:`.Inspector.get_view_names` + + """ + + with self._operation_context() as conn: + return self.dialect.get_materialized_view_names( + conn, schema, info_cache=self.info_cache, **kw + ) + + def get_sequence_names( + self, schema: Optional[str] = None, **kw: Any + ) -> List[str]: + r"""Return all sequence names in `schema`. + + :param schema: Optional, retrieve names from a non-default schema. + For special quoting, use :class:`.quoted_name`. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + """ + + with self._operation_context() as conn: + return self.dialect.get_sequence_names( + conn, schema, info_cache=self.info_cache, **kw + ) + + def get_view_definition( + self, view_name: str, schema: Optional[str] = None, **kw: Any + ) -> str: + r"""Return definition for the plain or materialized view called + ``view_name``. + + :param view_name: Name of the view. + :param schema: Optional, retrieve names from a non-default schema. + For special quoting, use :class:`.quoted_name`. + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + """ + + with self._operation_context() as conn: + return self.dialect.get_view_definition( + conn, view_name, schema, info_cache=self.info_cache, **kw + ) + + def get_columns( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> List[ReflectedColumn]: + r"""Return information about columns in ``table_name``. + + Given a string ``table_name`` and an optional string ``schema``, + return column information as a list of :class:`.ReflectedColumn`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: list of dictionaries, each representing the definition of + a database column. + + .. seealso:: :meth:`Inspector.get_multi_columns`. + + """ + + with self._operation_context() as conn: + col_defs = self.dialect.get_columns( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + if col_defs: + self._instantiate_types([col_defs]) + return col_defs + + def _instantiate_types( + self, data: Iterable[List[ReflectedColumn]] + ) -> None: + # make this easy and only return instances for coltype + for col_defs in data: + for col_def in col_defs: + coltype = col_def["type"] + if not isinstance(coltype, TypeEngine): + col_def["type"] = coltype() + + def get_multi_columns( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, List[ReflectedColumn]]: + r"""Return information about columns in all objects in the given + schema. + + The objects can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a list of :class:`.ReflectedColumn`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if columns of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of a database column. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_columns` + """ + + with self._operation_context() as conn: + table_col_defs = dict( + self.dialect.get_multi_columns( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + self._instantiate_types(table_col_defs.values()) + return table_col_defs + + def get_pk_constraint( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> ReflectedPrimaryKeyConstraint: + r"""Return information about primary key constraint in ``table_name``. + + Given a string ``table_name``, and an optional string `schema`, return + primary key information as a :class:`.ReflectedPrimaryKeyConstraint`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary representing the definition of + a primary key constraint. + + .. seealso:: :meth:`Inspector.get_multi_pk_constraint` + """ + with self._operation_context() as conn: + return self.dialect.get_pk_constraint( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_pk_constraint( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, ReflectedPrimaryKeyConstraint]: + r"""Return information about primary key constraints in + all tables in the given schema. + + The tables can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a :class:`.ReflectedPrimaryKeyConstraint`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if primary keys of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are dictionaries, each representing the + definition of a primary key constraint. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_pk_constraint` + """ + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_pk_constraint( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def get_foreign_keys( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> List[ReflectedForeignKeyConstraint]: + r"""Return information about foreign_keys in ``table_name``. + + Given a string ``table_name``, and an optional string `schema`, return + foreign key information as a list of + :class:`.ReflectedForeignKeyConstraint`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a list of dictionaries, each representing the + a foreign key definition. + + .. seealso:: :meth:`Inspector.get_multi_foreign_keys` + """ + + with self._operation_context() as conn: + return self.dialect.get_foreign_keys( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_foreign_keys( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, List[ReflectedForeignKeyConstraint]]: + r"""Return information about foreign_keys in all tables + in the given schema. + + The tables can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a list of + :class:`.ReflectedForeignKeyConstraint`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if foreign keys of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing + a foreign key definition. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_foreign_keys` + """ + + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_foreign_keys( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def get_indexes( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> List[ReflectedIndex]: + r"""Return information about indexes in ``table_name``. + + Given a string ``table_name`` and an optional string `schema`, return + index information as a list of :class:`.ReflectedIndex`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a list of dictionaries, each representing the + definition of an index. + + .. seealso:: :meth:`Inspector.get_multi_indexes` + """ + + with self._operation_context() as conn: + return self.dialect.get_indexes( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_indexes( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, List[ReflectedIndex]]: + r"""Return information about indexes in in all objects + in the given schema. + + The objects can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a list of :class:`.ReflectedIndex`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if indexes of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of an index. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_indexes` + """ + + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_indexes( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def get_unique_constraints( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> List[ReflectedUniqueConstraint]: + r"""Return information about unique constraints in ``table_name``. + + Given a string ``table_name`` and an optional string `schema`, return + unique constraint information as a list of + :class:`.ReflectedUniqueConstraint`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a list of dictionaries, each representing the + definition of an unique constraint. + + .. seealso:: :meth:`Inspector.get_multi_unique_constraints` + """ + + with self._operation_context() as conn: + return self.dialect.get_unique_constraints( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_unique_constraints( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, List[ReflectedUniqueConstraint]]: + r"""Return information about unique constraints in all tables + in the given schema. + + The tables can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a list of + :class:`.ReflectedUniqueConstraint`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if constraints of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of an unique constraint. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_unique_constraints` + """ + + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_unique_constraints( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def get_table_comment( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> ReflectedTableComment: + r"""Return information about the table comment for ``table_name``. + + Given a string ``table_name`` and an optional string ``schema``, + return table comment information as a :class:`.ReflectedTableComment`. + + Raises ``NotImplementedError`` for a dialect that does not support + comments. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary, with the table comment. + + .. versionadded:: 1.2 + + .. seealso:: :meth:`Inspector.get_multi_table_comment` + """ + + with self._operation_context() as conn: + return self.dialect.get_table_comment( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_table_comment( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, ReflectedTableComment]: + r"""Return information about the table comment in all objects + in the given schema. + + The objects can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a :class:`.ReflectedTableComment`. + + Raises ``NotImplementedError`` for a dialect that does not support + comments. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if comments of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are dictionaries, representing the + table comments. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_table_comment` + """ + + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_table_comment( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def get_check_constraints( + self, table_name: str, schema: Optional[str] = None, **kw: Any + ) -> List[ReflectedCheckConstraint]: + r"""Return information about check constraints in ``table_name``. + + Given a string ``table_name`` and an optional string `schema`, return + check constraint information as a list of + :class:`.ReflectedCheckConstraint`. + + :param table_name: string name of the table. For special quoting, + use :class:`.quoted_name`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a list of dictionaries, each representing the + definition of a check constraints. + + .. seealso:: :meth:`Inspector.get_multi_check_constraints` + """ + + with self._operation_context() as conn: + return self.dialect.get_check_constraints( + conn, table_name, schema, info_cache=self.info_cache, **kw + ) + + def get_multi_check_constraints( + self, + schema: Optional[str] = None, + filter_names: Optional[Sequence[str]] = None, + kind: ObjectKind = ObjectKind.TABLE, + scope: ObjectScope = ObjectScope.DEFAULT, + **kw: Any, + ) -> Dict[TableKey, List[ReflectedCheckConstraint]]: + r"""Return information about check constraints in all tables + in the given schema. + + The tables can be filtered by passing the names to use to + ``filter_names``. + + For each table the value is a list of + :class:`.ReflectedCheckConstraint`. + + :param schema: string schema name; if omitted, uses the default schema + of the database connection. For special quoting, + use :class:`.quoted_name`. + + :param filter_names: optionally return information only for the + objects listed here. + + :param kind: a :class:`.ObjectKind` that specifies the type of objects + to reflect. Defaults to ``ObjectKind.TABLE``. + + :param scope: a :class:`.ObjectScope` that specifies if constraints of + default, temporary or any tables should be reflected. + Defaults to ``ObjectScope.DEFAULT``. + + :param \**kw: Additional keyword argument to pass to the dialect + specific implementation. See the documentation of the dialect + in use for more information. + + :return: a dictionary where the keys are two-tuple schema,table-name + and the values are list of dictionaries, each representing the + definition of a check constraints. + The schema is ``None`` if no schema is provided. + + .. versionadded:: 2.0 + + .. seealso:: :meth:`Inspector.get_check_constraints` + """ + + with self._operation_context() as conn: + return dict( + self.dialect.get_multi_check_constraints( + conn, + schema=schema, + filter_names=filter_names, + kind=kind, + scope=scope, + info_cache=self.info_cache, + **kw, + ) + ) + + def reflect_table( + self, + table: sa_schema.Table, + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str] = (), + resolve_fks: bool = True, + _extend_on: Optional[Set[sa_schema.Table]] = None, + _reflect_info: Optional[_ReflectionInfo] = None, + ) -> None: + """Given a :class:`_schema.Table` object, load its internal + constructs based on introspection. + + This is the underlying method used by most dialects to produce + table reflection. Direct usage is like:: + + from sqlalchemy import create_engine, MetaData, Table + from sqlalchemy import inspect + + engine = create_engine("...") + meta = MetaData() + user_table = Table("user", meta) + insp = inspect(engine) + insp.reflect_table(user_table, None) + + .. versionchanged:: 1.4 Renamed from ``reflecttable`` to + ``reflect_table`` + + :param table: a :class:`~sqlalchemy.schema.Table` instance. + :param include_columns: a list of string column names to include + in the reflection process. If ``None``, all columns are reflected. + + """ + + if _extend_on is not None: + if table in _extend_on: + return + else: + _extend_on.add(table) + + dialect = self.bind.dialect + + with self._operation_context() as conn: + schema = conn.schema_for_object(table) + + table_name = table.name + + # get table-level arguments that are specifically + # intended for reflection, e.g. oracle_resolve_synonyms. + # these are unconditionally passed to related Table + # objects + reflection_options = { + k: table.dialect_kwargs.get(k) + for k in dialect.reflection_options + if k in table.dialect_kwargs + } + + table_key = (schema, table_name) + if _reflect_info is None or table_key not in _reflect_info.columns: + _reflect_info = self._get_reflection_info( + schema, + filter_names=[table_name], + kind=ObjectKind.ANY, + scope=ObjectScope.ANY, + _reflect_info=_reflect_info, + **table.dialect_kwargs, + ) + if table_key in _reflect_info.unreflectable: + raise _reflect_info.unreflectable[table_key] + + if table_key not in _reflect_info.columns: + raise exc.NoSuchTableError(table_name) + + # reflect table options, like mysql_engine + if _reflect_info.table_options: + tbl_opts = _reflect_info.table_options.get(table_key) + if tbl_opts: + # add additional kwargs to the Table if the dialect + # returned them + table._validate_dialect_kwargs(tbl_opts) + + found_table = False + cols_by_orig_name: Dict[str, sa_schema.Column[Any]] = {} + + for col_d in _reflect_info.columns[table_key]: + found_table = True + + self._reflect_column( + table, + col_d, + include_columns, + exclude_columns, + cols_by_orig_name, + ) + + # NOTE: support tables/views with no columns + if not found_table and not self.has_table(table_name, schema): + raise exc.NoSuchTableError(table_name) + + self._reflect_pk( + _reflect_info, table_key, table, cols_by_orig_name, exclude_columns + ) + + self._reflect_fk( + _reflect_info, + table_key, + table, + cols_by_orig_name, + include_columns, + exclude_columns, + resolve_fks, + _extend_on, + reflection_options, + ) + + self._reflect_indexes( + _reflect_info, + table_key, + table, + cols_by_orig_name, + include_columns, + exclude_columns, + reflection_options, + ) + + self._reflect_unique_constraints( + _reflect_info, + table_key, + table, + cols_by_orig_name, + include_columns, + exclude_columns, + reflection_options, + ) + + self._reflect_check_constraints( + _reflect_info, + table_key, + table, + cols_by_orig_name, + include_columns, + exclude_columns, + reflection_options, + ) + + self._reflect_table_comment( + _reflect_info, + table_key, + table, + reflection_options, + ) + + def _reflect_column( + self, + table: sa_schema.Table, + col_d: ReflectedColumn, + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str], + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + ) -> None: + orig_name = col_d["name"] + + table.metadata.dispatch.column_reflect(self, table, col_d) + table.dispatch.column_reflect(self, table, col_d) + + # fetch name again as column_reflect is allowed to + # change it + name = col_d["name"] + if (include_columns and name not in include_columns) or ( + exclude_columns and name in exclude_columns + ): + return + + coltype = col_d["type"] + + col_kw = { + k: col_d[k] # type: ignore[literal-required] + for k in [ + "nullable", + "autoincrement", + "quote", + "info", + "key", + "comment", + ] + if k in col_d + } + + if "dialect_options" in col_d: + col_kw.update(col_d["dialect_options"]) + + colargs = [] + default: Any + if col_d.get("default") is not None: + default_text = col_d["default"] + assert default_text is not None + if isinstance(default_text, TextClause): + default = sa_schema.DefaultClause( + default_text, _reflected=True + ) + elif not isinstance(default_text, sa_schema.FetchedValue): + default = sa_schema.DefaultClause( + sql.text(default_text), _reflected=True + ) + else: + default = default_text + colargs.append(default) + + if "computed" in col_d: + computed = sa_schema.Computed(**col_d["computed"]) + colargs.append(computed) + + if "identity" in col_d: + identity = sa_schema.Identity(**col_d["identity"]) + colargs.append(identity) + + cols_by_orig_name[orig_name] = col = sa_schema.Column( + name, coltype, *colargs, **col_kw + ) + + if col.key in table.primary_key: + col.primary_key = True + table.append_column(col, replace_existing=True) + + def _reflect_pk( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + exclude_columns: Collection[str], + ) -> None: + pk_cons = _reflect_info.pk_constraint.get(table_key) + if pk_cons: + pk_cols = [ + cols_by_orig_name[pk] + for pk in pk_cons["constrained_columns"] + if pk in cols_by_orig_name and pk not in exclude_columns + ] + + # update pk constraint name, comment and dialect_kwargs + table.primary_key.name = pk_cons.get("name") + table.primary_key.comment = pk_cons.get("comment", None) + dialect_options = pk_cons.get("dialect_options") + if dialect_options: + table.primary_key.dialect_kwargs.update(dialect_options) + + # tell the PKConstraint to re-initialize + # its column collection + table.primary_key._reload(pk_cols) + + def _reflect_fk( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str], + resolve_fks: bool, + _extend_on: Optional[Set[sa_schema.Table]], + reflection_options: Dict[str, Any], + ) -> None: + fkeys = _reflect_info.foreign_keys.get(table_key, []) + for fkey_d in fkeys: + conname = fkey_d["name"] + # look for columns by orig name in cols_by_orig_name, + # but support columns that are in-Python only as fallback + constrained_columns = [ + cols_by_orig_name[c].key if c in cols_by_orig_name else c + for c in fkey_d["constrained_columns"] + ] + + if ( + exclude_columns + and set(constrained_columns).intersection(exclude_columns) + or ( + include_columns + and set(constrained_columns).difference(include_columns) + ) + ): + continue + + referred_schema = fkey_d["referred_schema"] + referred_table = fkey_d["referred_table"] + referred_columns = fkey_d["referred_columns"] + refspec = [] + if referred_schema is not None: + if resolve_fks: + sa_schema.Table( + referred_table, + table.metadata, + schema=referred_schema, + autoload_with=self.bind, + _extend_on=_extend_on, + _reflect_info=_reflect_info, + **reflection_options, + ) + for column in referred_columns: + refspec.append( + ".".join([referred_schema, referred_table, column]) + ) + else: + if resolve_fks: + sa_schema.Table( + referred_table, + table.metadata, + autoload_with=self.bind, + schema=sa_schema.BLANK_SCHEMA, + _extend_on=_extend_on, + _reflect_info=_reflect_info, + **reflection_options, + ) + for column in referred_columns: + refspec.append(".".join([referred_table, column])) + if "options" in fkey_d: + options = fkey_d["options"] + else: + options = {} + + try: + table.append_constraint( + sa_schema.ForeignKeyConstraint( + constrained_columns, + refspec, + conname, + link_to_name=True, + comment=fkey_d.get("comment"), + **options, + ) + ) + except exc.ConstraintColumnNotFoundError: + util.warn( + f"On reflected table {table.name}, skipping reflection of " + "foreign key constraint " + f"{conname}; one or more subject columns within " + f"name(s) {', '.join(constrained_columns)} are not " + "present in the table" + ) + + _index_sort_exprs = { + "asc": operators.asc_op, + "desc": operators.desc_op, + "nulls_first": operators.nulls_first_op, + "nulls_last": operators.nulls_last_op, + } + + def _reflect_indexes( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str], + reflection_options: Dict[str, Any], + ) -> None: + # Indexes + indexes = _reflect_info.indexes.get(table_key, []) + for index_d in indexes: + name = index_d["name"] + columns = index_d["column_names"] + expressions = index_d.get("expressions") + column_sorting = index_d.get("column_sorting", {}) + unique = index_d["unique"] + flavor = index_d.get("type", "index") + dialect_options = index_d.get("dialect_options", {}) + + duplicates = index_d.get("duplicates_constraint") + if include_columns and not set(columns).issubset(include_columns): + continue + if duplicates: + continue + # look for columns by orig name in cols_by_orig_name, + # but support columns that are in-Python only as fallback + idx_element: Any + idx_elements = [] + for index, c in enumerate(columns): + if c is None: + if not expressions: + util.warn( + f"Skipping {flavor} {name!r} because key " + f"{index + 1} reflected as None but no " + "'expressions' were returned" + ) + break + idx_element = sql.text(expressions[index]) + else: + try: + if c in cols_by_orig_name: + idx_element = cols_by_orig_name[c] + else: + idx_element = table.c[c] + except KeyError: + util.warn( + f"{flavor} key {c!r} was not located in " + f"columns for table {table.name!r}" + ) + continue + for option in column_sorting.get(c, ()): + if option in self._index_sort_exprs: + op = self._index_sort_exprs[option] + idx_element = op(idx_element) + idx_elements.append(idx_element) + else: + sa_schema.Index( + name, + *idx_elements, + _table=table, + unique=unique, + **dialect_options, + ) + + def _reflect_unique_constraints( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str], + reflection_options: Dict[str, Any], + ) -> None: + constraints = _reflect_info.unique_constraints.get(table_key, []) + # Unique Constraints + for const_d in constraints: + conname = const_d["name"] + columns = const_d["column_names"] + comment = const_d.get("comment") + duplicates = const_d.get("duplicates_index") + dialect_options = const_d.get("dialect_options", {}) + if include_columns and not set(columns).issubset(include_columns): + continue + if duplicates: + continue + # look for columns by orig name in cols_by_orig_name, + # but support columns that are in-Python only as fallback + constrained_cols = [] + for c in columns: + try: + constrained_col = ( + cols_by_orig_name[c] + if c in cols_by_orig_name + else table.c[c] + ) + except KeyError: + util.warn( + "unique constraint key '%s' was not located in " + "columns for table '%s'" % (c, table.name) + ) + else: + constrained_cols.append(constrained_col) + table.append_constraint( + sa_schema.UniqueConstraint( + *constrained_cols, + name=conname, + comment=comment, + **dialect_options, + ) + ) + + def _reflect_check_constraints( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + cols_by_orig_name: Dict[str, sa_schema.Column[Any]], + include_columns: Optional[Collection[str]], + exclude_columns: Collection[str], + reflection_options: Dict[str, Any], + ) -> None: + constraints = _reflect_info.check_constraints.get(table_key, []) + for const_d in constraints: + table.append_constraint(sa_schema.CheckConstraint(**const_d)) + + def _reflect_table_comment( + self, + _reflect_info: _ReflectionInfo, + table_key: TableKey, + table: sa_schema.Table, + reflection_options: Dict[str, Any], + ) -> None: + comment_dict = _reflect_info.table_comment.get(table_key) + if comment_dict: + table.comment = comment_dict["text"] + + def _get_reflection_info( + self, + schema: Optional[str] = None, + filter_names: Optional[Collection[str]] = None, + available: Optional[Collection[str]] = None, + _reflect_info: Optional[_ReflectionInfo] = None, + **kw: Any, + ) -> _ReflectionInfo: + kw["schema"] = schema + + if filter_names and available and len(filter_names) > 100: + fraction = len(filter_names) / len(available) + else: + fraction = None + + unreflectable: Dict[TableKey, exc.UnreflectableTableError] + kw["unreflectable"] = unreflectable = {} + + has_result: bool = True + + def run( + meth: Any, + *, + optional: bool = False, + check_filter_names_from_meth: bool = False, + ) -> Any: + nonlocal has_result + # simple heuristic to improve reflection performance if a + # dialect implements multi_reflection: + # if more than 50% of the tables in the db are in filter_names + # load all the tables, since it's most likely faster to avoid + # a filter on that many tables. + if ( + fraction is None + or fraction <= 0.5 + or not self.dialect._overrides_default(meth.__name__) + ): + _fn = filter_names + else: + _fn = None + try: + if has_result: + res = meth(filter_names=_fn, **kw) + if check_filter_names_from_meth and not res: + # method returned no result data. + # skip any future call methods + has_result = False + else: + res = {} + except NotImplementedError: + if not optional: + raise + res = {} + return res + + info = _ReflectionInfo( + columns=run( + self.get_multi_columns, check_filter_names_from_meth=True + ), + pk_constraint=run(self.get_multi_pk_constraint), + foreign_keys=run(self.get_multi_foreign_keys), + indexes=run(self.get_multi_indexes), + unique_constraints=run( + self.get_multi_unique_constraints, optional=True + ), + table_comment=run(self.get_multi_table_comment, optional=True), + check_constraints=run( + self.get_multi_check_constraints, optional=True + ), + table_options=run(self.get_multi_table_options, optional=True), + unreflectable=unreflectable, + ) + if _reflect_info: + _reflect_info.update(info) + return _reflect_info + else: + return info + + +@final +class ReflectionDefaults: + """provides blank default values for reflection methods.""" + + @classmethod + def columns(cls) -> List[ReflectedColumn]: + return [] + + @classmethod + def pk_constraint(cls) -> ReflectedPrimaryKeyConstraint: + return { + "name": None, + "constrained_columns": [], + } + + @classmethod + def foreign_keys(cls) -> List[ReflectedForeignKeyConstraint]: + return [] + + @classmethod + def indexes(cls) -> List[ReflectedIndex]: + return [] + + @classmethod + def unique_constraints(cls) -> List[ReflectedUniqueConstraint]: + return [] + + @classmethod + def check_constraints(cls) -> List[ReflectedCheckConstraint]: + return [] + + @classmethod + def table_options(cls) -> Dict[str, Any]: + return {} + + @classmethod + def table_comment(cls) -> ReflectedTableComment: + return {"text": None} + + +@dataclass +class _ReflectionInfo: + columns: Dict[TableKey, List[ReflectedColumn]] + pk_constraint: Dict[TableKey, Optional[ReflectedPrimaryKeyConstraint]] + foreign_keys: Dict[TableKey, List[ReflectedForeignKeyConstraint]] + indexes: Dict[TableKey, List[ReflectedIndex]] + # optionals + unique_constraints: Dict[TableKey, List[ReflectedUniqueConstraint]] + table_comment: Dict[TableKey, Optional[ReflectedTableComment]] + check_constraints: Dict[TableKey, List[ReflectedCheckConstraint]] + table_options: Dict[TableKey, Dict[str, Any]] + unreflectable: Dict[TableKey, exc.UnreflectableTableError] + + def update(self, other: _ReflectionInfo) -> None: + for k, v in self.__dict__.items(): + ov = getattr(other, k) + if ov is not None: + if v is None: + setattr(self, k, ov) + else: + v.update(ov) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/result.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/result.py new file mode 100644 index 0000000000000000000000000000000000000000..17651f1e58dc3fad632f63208349242f9a86053c --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/result.py @@ -0,0 +1,2422 @@ +# engine/result.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Define generic result set constructs.""" + +from __future__ import annotations + +from enum import Enum +import functools +import itertools +import operator +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .row import Row +from .row import RowMapping +from .. import exc +from .. import util +from ..sql.base import _generative +from ..sql.base import HasMemoized +from ..sql.base import InPlaceGenerative +from ..util import HasMemoized_ro_memoized_attribute +from ..util import NONE_SET +from ..util._has_cy import HAS_CYEXTENSION +from ..util.typing import Literal +from ..util.typing import Self + +if typing.TYPE_CHECKING or not HAS_CYEXTENSION: + from ._py_row import tuplegetter as tuplegetter +else: + from sqlalchemy.cyextension.resultproxy import tuplegetter as tuplegetter + +if typing.TYPE_CHECKING: + from typing import Type + + from .. import inspection + from ..sql import roles + from ..sql._typing import _HasClauseElement + from ..sql.elements import SQLCoreOperations + from ..sql.type_api import _ResultProcessorType + +_KeyType = Union[ + str, + "SQLCoreOperations[Any]", + "roles.TypedColumnsClauseRole[Any]", + "roles.ColumnsClauseRole", + "Type[Any]", + "inspection.Inspectable[_HasClauseElement[Any]]", +] +_KeyIndexType = Union[_KeyType, int] + +# is overridden in cursor using _CursorKeyMapRecType +_KeyMapRecType = Any + +_KeyMapType = Mapping[_KeyType, _KeyMapRecType] + + +_RowData = Union[Row[Any], RowMapping, Any] +"""A generic form of "row" that accommodates for the different kinds of +"rows" that different result objects return, including row, row mapping, and +scalar values""" + +_RawRowType = Tuple[Any, ...] +"""represents the kind of row we get from a DBAPI cursor""" + +_R = TypeVar("_R", bound=_RowData) +_T = TypeVar("_T", bound=Any) +_TP = TypeVar("_TP", bound=Tuple[Any, ...]) + +_InterimRowType = Union[_R, _RawRowType] +"""a catchall "anything" kind of return type that can be applied +across all the result types + +""" + +_InterimSupportsScalarsRowType = Union[Row[Any], Any] + +_ProcessorsType = Sequence[Optional["_ResultProcessorType[Any]"]] +_TupleGetterType = Callable[[Sequence[Any]], Sequence[Any]] +_UniqueFilterType = Callable[[Any], Any] +_UniqueFilterStateType = Tuple[Set[Any], Optional[_UniqueFilterType]] + + +class ResultMetaData: + """Base for metadata about result rows.""" + + __slots__ = () + + _tuplefilter: Optional[_TupleGetterType] = None + _translated_indexes: Optional[Sequence[int]] = None + _unique_filters: Optional[Sequence[Callable[[Any], Any]]] = None + _keymap: _KeyMapType + _keys: Sequence[str] + _processors: Optional[_ProcessorsType] + _key_to_index: Mapping[_KeyType, int] + + @property + def keys(self) -> RMKeyView: + return RMKeyView(self) + + def _has_key(self, key: object) -> bool: + raise NotImplementedError() + + def _for_freeze(self) -> ResultMetaData: + raise NotImplementedError() + + @overload + def _key_fallback( + self, key: Any, err: Optional[Exception], raiseerr: Literal[True] = ... + ) -> NoReturn: ... + + @overload + def _key_fallback( + self, + key: Any, + err: Optional[Exception], + raiseerr: Literal[False] = ..., + ) -> None: ... + + @overload + def _key_fallback( + self, key: Any, err: Optional[Exception], raiseerr: bool = ... + ) -> Optional[NoReturn]: ... + + def _key_fallback( + self, key: Any, err: Optional[Exception], raiseerr: bool = True + ) -> Optional[NoReturn]: + assert raiseerr + raise KeyError(key) from err + + def _raise_for_ambiguous_column_name( + self, rec: _KeyMapRecType + ) -> NoReturn: + raise NotImplementedError( + "ambiguous column name logic is implemented for " + "CursorResultMetaData" + ) + + def _index_for_key( + self, key: _KeyIndexType, raiseerr: bool + ) -> Optional[int]: + raise NotImplementedError() + + def _indexes_for_keys( + self, keys: Sequence[_KeyIndexType] + ) -> Sequence[int]: + raise NotImplementedError() + + def _metadata_for_keys( + self, keys: Sequence[_KeyIndexType] + ) -> Iterator[_KeyMapRecType]: + raise NotImplementedError() + + def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData: + raise NotImplementedError() + + def _getter( + self, key: Any, raiseerr: bool = True + ) -> Optional[Callable[[Row[Any]], Any]]: + index = self._index_for_key(key, raiseerr) + + if index is not None: + return operator.itemgetter(index) + else: + return None + + def _row_as_tuple_getter( + self, keys: Sequence[_KeyIndexType] + ) -> _TupleGetterType: + indexes = self._indexes_for_keys(keys) + return tuplegetter(*indexes) + + def _make_key_to_index( + self, keymap: Mapping[_KeyType, Sequence[Any]], index: int + ) -> Mapping[_KeyType, int]: + return { + key: rec[index] + for key, rec in keymap.items() + if rec[index] is not None + } + + def _key_not_found(self, key: Any, attr_error: bool) -> NoReturn: + if key in self._keymap: + # the index must be none in this case + self._raise_for_ambiguous_column_name(self._keymap[key]) + else: + # unknown key + if attr_error: + try: + self._key_fallback(key, None) + except KeyError as ke: + raise AttributeError(ke.args[0]) from ke + else: + self._key_fallback(key, None) + + @property + def _effective_processors(self) -> Optional[_ProcessorsType]: + if not self._processors or NONE_SET.issuperset(self._processors): + return None + else: + return self._processors + + +class RMKeyView(typing.KeysView[Any]): + __slots__ = ("_parent", "_keys") + + _parent: ResultMetaData + _keys: Sequence[str] + + def __init__(self, parent: ResultMetaData): + self._parent = parent + self._keys = [k for k in parent._keys if k is not None] + + def __len__(self) -> int: + return len(self._keys) + + def __repr__(self) -> str: + return "{0.__class__.__name__}({0._keys!r})".format(self) + + def __iter__(self) -> Iterator[str]: + return iter(self._keys) + + def __contains__(self, item: Any) -> bool: + if isinstance(item, int): + return False + + # note this also includes special key fallback behaviors + # which also don't seem to be tested in test_resultset right now + return self._parent._has_key(item) + + def __eq__(self, other: Any) -> bool: + return list(other) == list(self) + + def __ne__(self, other: Any) -> bool: + return list(other) != list(self) + + +class SimpleResultMetaData(ResultMetaData): + """result metadata for in-memory collections.""" + + __slots__ = ( + "_keys", + "_keymap", + "_processors", + "_tuplefilter", + "_translated_indexes", + "_unique_filters", + "_key_to_index", + ) + + _keys: Sequence[str] + + def __init__( + self, + keys: Sequence[str], + extra: Optional[Sequence[Any]] = None, + _processors: Optional[_ProcessorsType] = None, + _tuplefilter: Optional[_TupleGetterType] = None, + _translated_indexes: Optional[Sequence[int]] = None, + _unique_filters: Optional[Sequence[Callable[[Any], Any]]] = None, + ): + self._keys = list(keys) + self._tuplefilter = _tuplefilter + self._translated_indexes = _translated_indexes + self._unique_filters = _unique_filters + if extra: + recs_names = [ + ( + (name,) + (extras if extras else ()), + (index, name, extras), + ) + for index, (name, extras) in enumerate(zip(self._keys, extra)) + ] + else: + recs_names = [ + ((name,), (index, name, ())) + for index, name in enumerate(self._keys) + ] + + self._keymap = {key: rec for keys, rec in recs_names for key in keys} + + self._processors = _processors + + self._key_to_index = self._make_key_to_index(self._keymap, 0) + + def _has_key(self, key: object) -> bool: + return key in self._keymap + + def _for_freeze(self) -> ResultMetaData: + unique_filters = self._unique_filters + if unique_filters and self._tuplefilter: + unique_filters = self._tuplefilter(unique_filters) + + # TODO: are we freezing the result with or without uniqueness + # applied? + return SimpleResultMetaData( + self._keys, + extra=[self._keymap[key][2] for key in self._keys], + _unique_filters=unique_filters, + ) + + def __getstate__(self) -> Dict[str, Any]: + return { + "_keys": self._keys, + "_translated_indexes": self._translated_indexes, + } + + def __setstate__(self, state: Dict[str, Any]) -> None: + if state["_translated_indexes"]: + _translated_indexes = state["_translated_indexes"] + _tuplefilter = tuplegetter(*_translated_indexes) + else: + _translated_indexes = _tuplefilter = None + self.__init__( # type: ignore + state["_keys"], + _translated_indexes=_translated_indexes, + _tuplefilter=_tuplefilter, + ) + + def _index_for_key(self, key: Any, raiseerr: bool = True) -> int: + if int in key.__class__.__mro__: + key = self._keys[key] + try: + rec = self._keymap[key] + except KeyError as ke: + rec = self._key_fallback(key, ke, raiseerr) + + return rec[0] # type: ignore[no-any-return] + + def _indexes_for_keys(self, keys: Sequence[Any]) -> Sequence[int]: + return [self._keymap[key][0] for key in keys] + + def _metadata_for_keys( + self, keys: Sequence[Any] + ) -> Iterator[_KeyMapRecType]: + for key in keys: + if int in key.__class__.__mro__: + key = self._keys[key] + + try: + rec = self._keymap[key] + except KeyError as ke: + rec = self._key_fallback(key, ke, True) + + yield rec + + def _reduce(self, keys: Sequence[Any]) -> ResultMetaData: + try: + metadata_for_keys = [ + self._keymap[ + self._keys[key] if int in key.__class__.__mro__ else key + ] + for key in keys + ] + except KeyError as ke: + self._key_fallback(ke.args[0], ke, True) + + indexes: Sequence[int] + new_keys: Sequence[str] + extra: Sequence[Any] + indexes, new_keys, extra = zip(*metadata_for_keys) + + if self._translated_indexes: + indexes = [self._translated_indexes[idx] for idx in indexes] + + tup = tuplegetter(*indexes) + + new_metadata = SimpleResultMetaData( + new_keys, + extra=extra, + _tuplefilter=tup, + _translated_indexes=indexes, + _processors=self._processors, + _unique_filters=self._unique_filters, + ) + + return new_metadata + + +def result_tuple( + fields: Sequence[str], extra: Optional[Any] = None +) -> Callable[[Iterable[Any]], Row[Any]]: + parent = SimpleResultMetaData(fields, extra) + return functools.partial( + Row, parent, parent._effective_processors, parent._key_to_index + ) + + +# a symbol that indicates to internal Result methods that +# "no row is returned". We can't use None for those cases where a scalar +# filter is applied to rows. +class _NoRow(Enum): + _NO_ROW = 0 + + +_NO_ROW = _NoRow._NO_ROW + + +class ResultInternal(InPlaceGenerative, Generic[_R]): + __slots__ = () + + _real_result: Optional[Result[Any]] = None + _generate_rows: bool = True + _row_logging_fn: Optional[Callable[[Any], Any]] + + _unique_filter_state: Optional[_UniqueFilterStateType] = None + _post_creational_filter: Optional[Callable[[Any], Any]] = None + _is_cursor = False + + _metadata: ResultMetaData + + _source_supports_scalars: bool + + def _fetchiter_impl(self) -> Iterator[_InterimRowType[Row[Any]]]: + raise NotImplementedError() + + def _fetchone_impl( + self, hard_close: bool = False + ) -> Optional[_InterimRowType[Row[Any]]]: + raise NotImplementedError() + + def _fetchmany_impl( + self, size: Optional[int] = None + ) -> List[_InterimRowType[Row[Any]]]: + raise NotImplementedError() + + def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]: + raise NotImplementedError() + + def _soft_close(self, hard: bool = False) -> None: + raise NotImplementedError() + + @HasMemoized_ro_memoized_attribute + def _row_getter(self) -> Optional[Callable[..., _R]]: + real_result: Result[Any] = ( + self._real_result + if self._real_result + else cast("Result[Any]", self) + ) + + if real_result._source_supports_scalars: + if not self._generate_rows: + return None + else: + _proc = Row + + def process_row( + metadata: ResultMetaData, + processors: Optional[_ProcessorsType], + key_to_index: Mapping[_KeyType, int], + scalar_obj: Any, + ) -> Row[Any]: + return _proc( + metadata, processors, key_to_index, (scalar_obj,) + ) + + else: + process_row = Row # type: ignore + + metadata = self._metadata + + key_to_index = metadata._key_to_index + processors = metadata._effective_processors + tf = metadata._tuplefilter + + if tf and not real_result._source_supports_scalars: + if processors: + processors = tf(processors) + + _make_row_orig: Callable[..., _R] = functools.partial( # type: ignore # noqa E501 + process_row, metadata, processors, key_to_index + ) + + fixed_tf = tf + + def make_row(row: _InterimRowType[Row[Any]]) -> _R: + return _make_row_orig(fixed_tf(row)) + + else: + make_row = functools.partial( # type: ignore + process_row, metadata, processors, key_to_index + ) + + if real_result._row_logging_fn: + _log_row = real_result._row_logging_fn + _make_row = make_row + + def make_row(row: _InterimRowType[Row[Any]]) -> _R: + return _log_row(_make_row(row)) # type: ignore + + return make_row + + @HasMemoized_ro_memoized_attribute + def _iterator_getter(self) -> Callable[..., Iterator[_R]]: + make_row = self._row_getter + + post_creational_filter = self._post_creational_filter + + if self._unique_filter_state: + uniques, strategy = self._unique_strategy + + def iterrows(self: Result[Any]) -> Iterator[_R]: + for raw_row in self._fetchiter_impl(): + obj: _InterimRowType[Any] = ( + make_row(raw_row) if make_row else raw_row + ) + hashed = strategy(obj) if strategy else obj + if hashed in uniques: + continue + uniques.add(hashed) + if post_creational_filter: + obj = post_creational_filter(obj) + yield obj # type: ignore + + else: + + def iterrows(self: Result[Any]) -> Iterator[_R]: + for raw_row in self._fetchiter_impl(): + row: _InterimRowType[Any] = ( + make_row(raw_row) if make_row else raw_row + ) + if post_creational_filter: + row = post_creational_filter(row) + yield row # type: ignore + + return iterrows + + def _raw_all_rows(self) -> List[_R]: + make_row = self._row_getter + assert make_row is not None + rows = self._fetchall_impl() + return [make_row(row) for row in rows] + + def _allrows(self) -> List[_R]: + post_creational_filter = self._post_creational_filter + + make_row = self._row_getter + + rows = self._fetchall_impl() + made_rows: List[_InterimRowType[_R]] + if make_row: + made_rows = [make_row(row) for row in rows] + else: + made_rows = rows # type: ignore + + interim_rows: List[_R] + + if self._unique_filter_state: + uniques, strategy = self._unique_strategy + + interim_rows = [ + made_row # type: ignore + for made_row, sig_row in [ + ( + made_row, + strategy(made_row) if strategy else made_row, + ) + for made_row in made_rows + ] + if sig_row not in uniques and not uniques.add(sig_row) # type: ignore # noqa: E501 + ] + else: + interim_rows = made_rows # type: ignore + + if post_creational_filter: + interim_rows = [ + post_creational_filter(row) for row in interim_rows + ] + return interim_rows + + @HasMemoized_ro_memoized_attribute + def _onerow_getter( + self, + ) -> Callable[..., Union[Literal[_NoRow._NO_ROW], _R]]: + make_row = self._row_getter + + post_creational_filter = self._post_creational_filter + + if self._unique_filter_state: + uniques, strategy = self._unique_strategy + + def onerow(self: Result[Any]) -> Union[_NoRow, _R]: + _onerow = self._fetchone_impl + while True: + row = _onerow() + if row is None: + return _NO_ROW + else: + obj: _InterimRowType[Any] = ( + make_row(row) if make_row else row + ) + hashed = strategy(obj) if strategy else obj + if hashed in uniques: + continue + else: + uniques.add(hashed) + if post_creational_filter: + obj = post_creational_filter(obj) + return obj # type: ignore + + else: + + def onerow(self: Result[Any]) -> Union[_NoRow, _R]: + row = self._fetchone_impl() + if row is None: + return _NO_ROW + else: + interim_row: _InterimRowType[Any] = ( + make_row(row) if make_row else row + ) + if post_creational_filter: + interim_row = post_creational_filter(interim_row) + return interim_row # type: ignore + + return onerow + + @HasMemoized_ro_memoized_attribute + def _manyrow_getter(self) -> Callable[..., List[_R]]: + make_row = self._row_getter + + post_creational_filter = self._post_creational_filter + + if self._unique_filter_state: + uniques, strategy = self._unique_strategy + + def filterrows( + make_row: Optional[Callable[..., _R]], + rows: List[Any], + strategy: Optional[Callable[[List[Any]], Any]], + uniques: Set[Any], + ) -> List[_R]: + if make_row: + rows = [make_row(row) for row in rows] + + if strategy: + made_rows = ( + (made_row, strategy(made_row)) for made_row in rows + ) + else: + made_rows = ((made_row, made_row) for made_row in rows) + return [ + made_row + for made_row, sig_row in made_rows + if sig_row not in uniques and not uniques.add(sig_row) # type: ignore # noqa: E501 + ] + + def manyrows( + self: ResultInternal[_R], num: Optional[int] + ) -> List[_R]: + collect: List[_R] = [] + + _manyrows = self._fetchmany_impl + + if num is None: + # if None is passed, we don't know the default + # manyrows number, DBAPI has this as cursor.arraysize + # different DBAPIs / fetch strategies may be different. + # do a fetch to find what the number is. if there are + # only fewer rows left, then it doesn't matter. + real_result = ( + self._real_result + if self._real_result + else cast("Result[Any]", self) + ) + if real_result._yield_per: + num_required = num = real_result._yield_per + else: + rows = _manyrows(num) + num = len(rows) + assert make_row is not None + collect.extend( + filterrows(make_row, rows, strategy, uniques) + ) + num_required = num - len(collect) + else: + num_required = num + + assert num is not None + + while num_required: + rows = _manyrows(num_required) + if not rows: + break + + collect.extend( + filterrows(make_row, rows, strategy, uniques) + ) + num_required = num - len(collect) + + if post_creational_filter: + collect = [post_creational_filter(row) for row in collect] + return collect + + else: + + def manyrows( + self: ResultInternal[_R], num: Optional[int] + ) -> List[_R]: + if num is None: + real_result = ( + self._real_result + if self._real_result + else cast("Result[Any]", self) + ) + num = real_result._yield_per + + rows: List[_InterimRowType[Any]] = self._fetchmany_impl(num) + if make_row: + rows = [make_row(row) for row in rows] + if post_creational_filter: + rows = [post_creational_filter(row) for row in rows] + return rows # type: ignore + + return manyrows + + @overload + def _only_one_row( + self: ResultInternal[Row[Any]], + raise_for_second_row: bool, + raise_for_none: bool, + scalar: Literal[True], + ) -> Any: ... + + @overload + def _only_one_row( + self, + raise_for_second_row: bool, + raise_for_none: Literal[True], + scalar: bool, + ) -> _R: ... + + @overload + def _only_one_row( + self, + raise_for_second_row: bool, + raise_for_none: bool, + scalar: bool, + ) -> Optional[_R]: ... + + def _only_one_row( + self, + raise_for_second_row: bool, + raise_for_none: bool, + scalar: bool, + ) -> Optional[_R]: + onerow = self._fetchone_impl + + row: Optional[_InterimRowType[Any]] = onerow(hard_close=True) + if row is None: + if raise_for_none: + raise exc.NoResultFound( + "No row was found when one was required" + ) + else: + return None + + if scalar and self._source_supports_scalars: + self._generate_rows = False + make_row = None + else: + make_row = self._row_getter + + try: + row = make_row(row) if make_row else row + except: + self._soft_close(hard=True) + raise + + if raise_for_second_row: + if self._unique_filter_state: + # for no second row but uniqueness, need to essentially + # consume the entire result :( + uniques, strategy = self._unique_strategy + + existing_row_hash = strategy(row) if strategy else row + + while True: + next_row: Any = onerow(hard_close=True) + if next_row is None: + next_row = _NO_ROW + break + + try: + next_row = make_row(next_row) if make_row else next_row + + if strategy: + assert next_row is not _NO_ROW + if existing_row_hash == strategy(next_row): + continue + elif row == next_row: + continue + # here, we have a row and it's different + break + except: + self._soft_close(hard=True) + raise + else: + next_row = onerow(hard_close=True) + if next_row is None: + next_row = _NO_ROW + + if next_row is not _NO_ROW: + self._soft_close(hard=True) + raise exc.MultipleResultsFound( + "Multiple rows were found when exactly one was required" + if raise_for_none + else "Multiple rows were found when one or none " + "was required" + ) + else: + # if we checked for second row then that would have + # closed us :) + self._soft_close(hard=True) + + if not scalar: + post_creational_filter = self._post_creational_filter + if post_creational_filter: + row = post_creational_filter(row) + + if scalar and make_row: + return row[0] # type: ignore + else: + return row # type: ignore + + def _iter_impl(self) -> Iterator[_R]: + return self._iterator_getter(self) + + def _next_impl(self) -> _R: + row = self._onerow_getter(self) + if row is _NO_ROW: + raise StopIteration() + else: + return row + + @_generative + def _column_slices(self, indexes: Sequence[_KeyIndexType]) -> Self: + real_result = ( + self._real_result + if self._real_result + else cast("Result[Any]", self) + ) + + if not real_result._source_supports_scalars or len(indexes) != 1: + self._metadata = self._metadata._reduce(indexes) + + assert self._generate_rows + + return self + + @HasMemoized.memoized_attribute + def _unique_strategy(self) -> _UniqueFilterStateType: + assert self._unique_filter_state is not None + uniques, strategy = self._unique_filter_state + + real_result = ( + self._real_result + if self._real_result is not None + else cast("Result[Any]", self) + ) + + if not strategy and self._metadata._unique_filters: + if ( + real_result._source_supports_scalars + and not self._generate_rows + ): + strategy = self._metadata._unique_filters[0] + else: + filters = self._metadata._unique_filters + if self._metadata._tuplefilter: + filters = self._metadata._tuplefilter(filters) + + strategy = operator.methodcaller("_filter_on_values", filters) + return uniques, strategy + + +class _WithKeys: + __slots__ = () + + _metadata: ResultMetaData + + # used mainly to share documentation on the keys method. + def keys(self) -> RMKeyView: + """Return an iterable view which yields the string keys that would + be represented by each :class:`_engine.Row`. + + The keys can represent the labels of the columns returned by a core + statement or the names of the orm classes returned by an orm + execution. + + The view also can be tested for key containment using the Python + ``in`` operator, which will test both for the string keys represented + in the view, as well as for alternate keys such as column objects. + + .. versionchanged:: 1.4 a key view object is returned rather than a + plain list. + + + """ + return self._metadata.keys + + +class Result(_WithKeys, ResultInternal[Row[_TP]]): + """Represent a set of database results. + + .. versionadded:: 1.4 The :class:`_engine.Result` object provides a + completely updated usage model and calling facade for SQLAlchemy + Core and SQLAlchemy ORM. In Core, it forms the basis of the + :class:`_engine.CursorResult` object which replaces the previous + :class:`_engine.ResultProxy` interface. When using the ORM, a + higher level object called :class:`_engine.ChunkedIteratorResult` + is normally used. + + .. note:: In SQLAlchemy 1.4 and above, this object is + used for ORM results returned by :meth:`_orm.Session.execute`, which can + yield instances of ORM mapped objects either individually or within + tuple-like rows. Note that the :class:`_engine.Result` object does not + deduplicate instances or rows automatically as is the case with the + legacy :class:`_orm.Query` object. For in-Python de-duplication of + instances or rows, use the :meth:`_engine.Result.unique` modifier + method. + + .. seealso:: + + :ref:`tutorial_fetching_rows` - in the :doc:`/tutorial/index` + + """ + + __slots__ = ("_metadata", "__dict__") + + _row_logging_fn: Optional[Callable[[Row[Any]], Row[Any]]] = None + + _source_supports_scalars: bool = False + + _yield_per: Optional[int] = None + + _attributes: util.immutabledict[Any, Any] = util.immutabledict() + + def __init__(self, cursor_metadata: ResultMetaData): + self._metadata = cursor_metadata + + def __enter__(self) -> Self: + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + self.close() + + def close(self) -> None: + """Hard close this :class:`_engine.Result`. + + The behavior of this method is implementation specific, and is + not implemented by default. The method should generally end + the resources in use by the result object and also cause any + subsequent iteration or row fetching to raise + :class:`.ResourceClosedError`. + + .. versionadded:: 1.4.27 - ``.close()`` was previously not generally + available for all :class:`_engine.Result` classes, instead only + being available on the :class:`_engine.CursorResult` returned for + Core statement executions. As most other result objects, namely the + ones used by the ORM, are proxying a :class:`_engine.CursorResult` + in any case, this allows the underlying cursor result to be closed + from the outside facade for the case when the ORM query is using + the ``yield_per`` execution option where it does not immediately + exhaust and autoclose the database cursor. + + """ + self._soft_close(hard=True) + + @property + def _soft_closed(self) -> bool: + raise NotImplementedError() + + @property + def closed(self) -> bool: + """Return ``True`` if this :class:`_engine.Result` was **hard closed** + by explicitly calling the :meth:`close` method. + + The attribute is **not** True if the :class:`_engine.Result` was only + **soft closed**; a "soft close" is the style of close that takes place + for example when the :class:`.CursorResult` is returned for a DML + only statement without RETURNING, or when all result rows are fetched. + + .. seealso:: + + :attr:`.CursorResult.returns_rows` - attribute specific to + :class:`.CursorResult` which indicates if the result is one that + may return zero or more rows + + """ + raise NotImplementedError() + + @_generative + def yield_per(self, num: int) -> Self: + """Configure the row-fetching strategy to fetch ``num`` rows at a time. + + This impacts the underlying behavior of the result when iterating over + the result object, or otherwise making use of methods such as + :meth:`_engine.Result.fetchone` that return one row at a time. Data + from the underlying cursor or other data source will be buffered up to + this many rows in memory, and the buffered collection will then be + yielded out one row at a time or as many rows are requested. Each time + the buffer clears, it will be refreshed to this many rows or as many + rows remain if fewer remain. + + The :meth:`_engine.Result.yield_per` method is generally used in + conjunction with the + :paramref:`_engine.Connection.execution_options.stream_results` + execution option, which will allow the database dialect in use to make + use of a server side cursor, if the DBAPI supports a specific "server + side cursor" mode separate from its default mode of operation. + + .. tip:: + + Consider using the + :paramref:`_engine.Connection.execution_options.yield_per` + execution option, which will simultaneously set + :paramref:`_engine.Connection.execution_options.stream_results` + to ensure the use of server side cursors, as well as automatically + invoke the :meth:`_engine.Result.yield_per` method to establish + a fixed row buffer size at once. + + The :paramref:`_engine.Connection.execution_options.yield_per` + execution option is available for ORM operations, with + :class:`_orm.Session`-oriented use described at + :ref:`orm_queryguide_yield_per`. The Core-only version which works + with :class:`_engine.Connection` is new as of SQLAlchemy 1.4.40. + + .. versionadded:: 1.4 + + :param num: number of rows to fetch each time the buffer is refilled. + If set to a value below 1, fetches all rows for the next buffer. + + .. seealso:: + + :ref:`engine_stream_results` - describes Core behavior for + :meth:`_engine.Result.yield_per` + + :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` + + """ + self._yield_per = num + return self + + @_generative + def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self: + """Apply unique filtering to the objects returned by this + :class:`_engine.Result`. + + When this filter is applied with no arguments, the rows or objects + returned will filtered such that each row is returned uniquely. The + algorithm used to determine this uniqueness is by default the Python + hashing identity of the whole tuple. In some cases a specialized + per-entity hashing scheme may be used, such as when using the ORM, a + scheme is applied which works against the primary key identity of + returned objects. + + The unique filter is applied **after all other filters**, which means + if the columns returned have been refined using a method such as the + :meth:`_engine.Result.columns` or :meth:`_engine.Result.scalars` + method, the uniquing is applied to **only the column or columns + returned**. This occurs regardless of the order in which these + methods have been called upon the :class:`_engine.Result` object. + + The unique filter also changes the calculus used for methods like + :meth:`_engine.Result.fetchmany` and :meth:`_engine.Result.partitions`. + When using :meth:`_engine.Result.unique`, these methods will continue + to yield the number of rows or objects requested, after uniquing + has been applied. However, this necessarily impacts the buffering + behavior of the underlying cursor or datasource, such that multiple + underlying calls to ``cursor.fetchmany()`` may be necessary in order + to accumulate enough objects in order to provide a unique collection + of the requested size. + + :param strategy: a callable that will be applied to rows or objects + being iterated, which should return an object that represents the + unique value of the row. A Python ``set()`` is used to store + these identities. If not passed, a default uniqueness strategy + is used which may have been assembled by the source of this + :class:`_engine.Result` object. + + """ + self._unique_filter_state = (set(), strategy) + return self + + def columns(self, *col_expressions: _KeyIndexType) -> Self: + r"""Establish the columns that should be returned in each row. + + This method may be used to limit the columns returned as well + as to reorder them. The given list of expressions are normally + a series of integers or string key names. They may also be + appropriate :class:`.ColumnElement` objects which correspond to + a given statement construct. + + .. versionchanged:: 2.0 Due to a bug in 1.4, the + :meth:`_engine.Result.columns` method had an incorrect behavior + where calling upon the method with just one index would cause the + :class:`_engine.Result` object to yield scalar values rather than + :class:`_engine.Row` objects. In version 2.0, this behavior + has been corrected such that calling upon + :meth:`_engine.Result.columns` with a single index will + produce a :class:`_engine.Result` object that continues + to yield :class:`_engine.Row` objects, which include + only a single column. + + E.g.:: + + statement = select(table.c.x, table.c.y, table.c.z) + result = connection.execute(statement) + + for z, y in result.columns("z", "y"): + ... + + Example of using the column objects from the statement itself:: + + for z, y in result.columns( + statement.selected_columns.c.z, statement.selected_columns.c.y + ): + ... + + .. versionadded:: 1.4 + + :param \*col_expressions: indicates columns to be returned. Elements + may be integer row indexes, string column names, or appropriate + :class:`.ColumnElement` objects corresponding to a select construct. + + :return: this :class:`_engine.Result` object with the modifications + given. + + """ + return self._column_slices(col_expressions) + + @overload + def scalars(self: Result[Tuple[_T]]) -> ScalarResult[_T]: ... + + @overload + def scalars( + self: Result[Tuple[_T]], index: Literal[0] + ) -> ScalarResult[_T]: ... + + @overload + def scalars(self, index: _KeyIndexType = 0) -> ScalarResult[Any]: ... + + def scalars(self, index: _KeyIndexType = 0) -> ScalarResult[Any]: + """Return a :class:`_engine.ScalarResult` filtering object which + will return single elements rather than :class:`_row.Row` objects. + + E.g.:: + + >>> result = conn.execute(text("select int_id from table")) + >>> result.scalars().all() + [1, 2, 3] + + When results are fetched from the :class:`_engine.ScalarResult` + filtering object, the single column-row that would be returned by the + :class:`_engine.Result` is instead returned as the column's value. + + .. versionadded:: 1.4 + + :param index: integer or row key indicating the column to be fetched + from each row, defaults to ``0`` indicating the first column. + + :return: a new :class:`_engine.ScalarResult` filtering object referring + to this :class:`_engine.Result` object. + + """ + return ScalarResult(self, index) + + def _getter( + self, key: _KeyIndexType, raiseerr: bool = True + ) -> Optional[Callable[[Row[Any]], Any]]: + """return a callable that will retrieve the given key from a + :class:`_engine.Row`. + + """ + if self._source_supports_scalars: + raise NotImplementedError( + "can't use this function in 'only scalars' mode" + ) + return self._metadata._getter(key, raiseerr) + + def _tuple_getter(self, keys: Sequence[_KeyIndexType]) -> _TupleGetterType: + """return a callable that will retrieve the given keys from a + :class:`_engine.Row`. + + """ + if self._source_supports_scalars: + raise NotImplementedError( + "can't use this function in 'only scalars' mode" + ) + return self._metadata._row_as_tuple_getter(keys) + + def mappings(self) -> MappingResult: + """Apply a mappings filter to returned rows, returning an instance of + :class:`_engine.MappingResult`. + + When this filter is applied, fetching rows will return + :class:`_engine.RowMapping` objects instead of :class:`_engine.Row` + objects. + + .. versionadded:: 1.4 + + :return: a new :class:`_engine.MappingResult` filtering object + referring to this :class:`_engine.Result` object. + + """ + + return MappingResult(self) + + @property + def t(self) -> TupleResult[_TP]: + """Apply a "typed tuple" typing filter to returned rows. + + The :attr:`_engine.Result.t` attribute is a synonym for + calling the :meth:`_engine.Result.tuples` method. + + .. versionadded:: 2.0 + + """ + return self # type: ignore + + def tuples(self) -> TupleResult[_TP]: + """Apply a "typed tuple" typing filter to returned rows. + + This method returns the same :class:`_engine.Result` object + at runtime, + however annotates as returning a :class:`_engine.TupleResult` object + that will indicate to :pep:`484` typing tools that plain typed + ``Tuple`` instances are returned rather than rows. This allows + tuple unpacking and ``__getitem__`` access of :class:`_engine.Row` + objects to by typed, for those cases where the statement invoked + itself included typing information. + + .. versionadded:: 2.0 + + :return: the :class:`_engine.TupleResult` type at typing time. + + .. seealso:: + + :attr:`_engine.Result.t` - shorter synonym + + :attr:`_engine.Row._t` - :class:`_engine.Row` version + + """ + + return self # type: ignore + + def _raw_row_iterator(self) -> Iterator[_RowData]: + """Return a safe iterator that yields raw row data. + + This is used by the :meth:`_engine.Result.merge` method + to merge multiple compatible results together. + + """ + raise NotImplementedError() + + def __iter__(self) -> Iterator[Row[_TP]]: + return self._iter_impl() + + def __next__(self) -> Row[_TP]: + return self._next_impl() + + def partitions( + self, size: Optional[int] = None + ) -> Iterator[Sequence[Row[_TP]]]: + """Iterate through sub-lists of rows of the size given. + + Each list will be of the size given, excluding the last list to + be yielded, which may have a small number of rows. No empty + lists will be yielded. + + The result object is automatically closed when the iterator + is fully consumed. + + Note that the backend driver will usually buffer the entire result + ahead of time unless the + :paramref:`.Connection.execution_options.stream_results` execution + option is used indicating that the driver should not pre-buffer + results, if possible. Not all drivers support this option and + the option is silently ignored for those who do not. + + When using the ORM, the :meth:`_engine.Result.partitions` method + is typically more effective from a memory perspective when it is + combined with use of the + :ref:`yield_per execution option `, + which instructs both the DBAPI driver to use server side cursors, + if available, as well as instructs the ORM loading internals to only + build a certain amount of ORM objects from a result at a time before + yielding them out. + + .. versionadded:: 1.4 + + :param size: indicate the maximum number of rows to be present + in each list yielded. If None, makes use of the value set by + the :meth:`_engine.Result.yield_per`, method, if it were called, + or the :paramref:`_engine.Connection.execution_options.yield_per` + execution option, which is equivalent in this regard. If + yield_per weren't set, it makes use of the + :meth:`_engine.Result.fetchmany` default, which may be backend + specific and not well defined. + + :return: iterator of lists + + .. seealso:: + + :ref:`engine_stream_results` + + :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` + + """ + + getter = self._manyrow_getter + + while True: + partition = getter(self, size) + if partition: + yield partition + else: + break + + def fetchall(self) -> Sequence[Row[_TP]]: + """A synonym for the :meth:`_engine.Result.all` method.""" + + return self._allrows() + + def fetchone(self) -> Optional[Row[_TP]]: + """Fetch one row. + + When all rows are exhausted, returns None. + + This method is provided for backwards compatibility with + SQLAlchemy 1.x.x. + + To fetch the first row of a result only, use the + :meth:`_engine.Result.first` method. To iterate through all + rows, iterate the :class:`_engine.Result` object directly. + + :return: a :class:`_engine.Row` object if no filters are applied, + or ``None`` if no rows remain. + + """ + row = self._onerow_getter(self) + if row is _NO_ROW: + return None + else: + return row + + def fetchmany(self, size: Optional[int] = None) -> Sequence[Row[_TP]]: + """Fetch many rows. + + When all rows are exhausted, returns an empty sequence. + + This method is provided for backwards compatibility with + SQLAlchemy 1.x.x. + + To fetch rows in groups, use the :meth:`_engine.Result.partitions` + method. + + :return: a sequence of :class:`_engine.Row` objects. + + .. seealso:: + + :meth:`_engine.Result.partitions` + + """ + + return self._manyrow_getter(self, size) + + def all(self) -> Sequence[Row[_TP]]: + """Return all rows in a sequence. + + Closes the result set after invocation. Subsequent invocations + will return an empty sequence. + + .. versionadded:: 1.4 + + :return: a sequence of :class:`_engine.Row` objects. + + .. seealso:: + + :ref:`engine_stream_results` - How to stream a large result set + without loading it completely in python. + + """ + + return self._allrows() + + def first(self) -> Optional[Row[_TP]]: + """Fetch the first row or ``None`` if no row is present. + + Closes the result set and discards remaining rows. + + .. note:: This method returns one **row**, e.g. tuple, by default. + To return exactly one single scalar value, that is, the first + column of the first row, use the + :meth:`_engine.Result.scalar` method, + or combine :meth:`_engine.Result.scalars` and + :meth:`_engine.Result.first`. + + Additionally, in contrast to the behavior of the legacy ORM + :meth:`_orm.Query.first` method, **no limit is applied** to the + SQL query which was invoked to produce this + :class:`_engine.Result`; + for a DBAPI driver that buffers results in memory before yielding + rows, all rows will be sent to the Python process and all but + the first row will be discarded. + + .. seealso:: + + :ref:`migration_20_unify_select` + + :return: a :class:`_engine.Row` object, or None + if no rows remain. + + .. seealso:: + + :meth:`_engine.Result.scalar` + + :meth:`_engine.Result.one` + + """ + + return self._only_one_row( + raise_for_second_row=False, raise_for_none=False, scalar=False + ) + + def one_or_none(self) -> Optional[Row[_TP]]: + """Return at most one result or raise an exception. + + Returns ``None`` if the result has no rows. + Raises :class:`.MultipleResultsFound` + if multiple rows are returned. + + .. versionadded:: 1.4 + + :return: The first :class:`_engine.Row` or ``None`` if no row + is available. + + :raises: :class:`.MultipleResultsFound` + + .. seealso:: + + :meth:`_engine.Result.first` + + :meth:`_engine.Result.one` + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=False, scalar=False + ) + + @overload + def scalar_one(self: Result[Tuple[_T]]) -> _T: ... + + @overload + def scalar_one(self) -> Any: ... + + def scalar_one(self) -> Any: + """Return exactly one scalar result or raise an exception. + + This is equivalent to calling :meth:`_engine.Result.scalars` and + then :meth:`_engine.ScalarResult.one`. + + .. seealso:: + + :meth:`_engine.ScalarResult.one` + + :meth:`_engine.Result.scalars` + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=True, scalar=True + ) + + @overload + def scalar_one_or_none(self: Result[Tuple[_T]]) -> Optional[_T]: ... + + @overload + def scalar_one_or_none(self) -> Optional[Any]: ... + + def scalar_one_or_none(self) -> Optional[Any]: + """Return exactly one scalar result or ``None``. + + This is equivalent to calling :meth:`_engine.Result.scalars` and + then :meth:`_engine.ScalarResult.one_or_none`. + + .. seealso:: + + :meth:`_engine.ScalarResult.one_or_none` + + :meth:`_engine.Result.scalars` + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=False, scalar=True + ) + + def one(self) -> Row[_TP]: + """Return exactly one row or raise an exception. + + Raises :class:`_exc.NoResultFound` if the result returns no + rows, or :class:`_exc.MultipleResultsFound` if multiple rows + would be returned. + + .. note:: This method returns one **row**, e.g. tuple, by default. + To return exactly one single scalar value, that is, the first + column of the first row, use the + :meth:`_engine.Result.scalar_one` method, or combine + :meth:`_engine.Result.scalars` and + :meth:`_engine.Result.one`. + + .. versionadded:: 1.4 + + :return: The first :class:`_engine.Row`. + + :raises: :class:`.MultipleResultsFound`, :class:`.NoResultFound` + + .. seealso:: + + :meth:`_engine.Result.first` + + :meth:`_engine.Result.one_or_none` + + :meth:`_engine.Result.scalar_one` + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=True, scalar=False + ) + + @overload + def scalar(self: Result[Tuple[_T]]) -> Optional[_T]: ... + + @overload + def scalar(self) -> Any: ... + + def scalar(self) -> Any: + """Fetch the first column of the first row, and close the result set. + + Returns ``None`` if there are no rows to fetch. + + No validation is performed to test if additional rows remain. + + After calling this method, the object is fully closed, + e.g. the :meth:`_engine.CursorResult.close` + method will have been called. + + :return: a Python scalar value, or ``None`` if no rows remain. + + """ + return self._only_one_row( + raise_for_second_row=False, raise_for_none=False, scalar=True + ) + + def freeze(self) -> FrozenResult[_TP]: + """Return a callable object that will produce copies of this + :class:`_engine.Result` when invoked. + + The callable object returned is an instance of + :class:`_engine.FrozenResult`. + + This is used for result set caching. The method must be called + on the result when it has been unconsumed, and calling the method + will consume the result fully. When the :class:`_engine.FrozenResult` + is retrieved from a cache, it can be called any number of times where + it will produce a new :class:`_engine.Result` object each time + against its stored set of rows. + + .. seealso:: + + :ref:`do_orm_execute_re_executing` - example usage within the + ORM to implement a result-set cache. + + """ + + return FrozenResult(self) + + def merge(self, *others: Result[Any]) -> MergedResult[_TP]: + """Merge this :class:`_engine.Result` with other compatible result + objects. + + The object returned is an instance of :class:`_engine.MergedResult`, + which will be composed of iterators from the given result + objects. + + The new result will use the metadata from this result object. + The subsequent result objects must be against an identical + set of result / cursor metadata, otherwise the behavior is + undefined. + + """ + return MergedResult(self._metadata, (self,) + others) + + +class FilterResult(ResultInternal[_R]): + """A wrapper for a :class:`_engine.Result` that returns objects other than + :class:`_engine.Row` objects, such as dictionaries or scalar objects. + + :class:`_engine.FilterResult` is the common base for additional result + APIs including :class:`_engine.MappingResult`, + :class:`_engine.ScalarResult` and :class:`_engine.AsyncResult`. + + """ + + __slots__ = ( + "_real_result", + "_post_creational_filter", + "_metadata", + "_unique_filter_state", + "__dict__", + ) + + _post_creational_filter: Optional[Callable[[Any], Any]] + + _real_result: Result[Any] + + def __enter__(self) -> Self: + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + self._real_result.__exit__(type_, value, traceback) + + @_generative + def yield_per(self, num: int) -> Self: + """Configure the row-fetching strategy to fetch ``num`` rows at a time. + + The :meth:`_engine.FilterResult.yield_per` method is a pass through + to the :meth:`_engine.Result.yield_per` method. See that method's + documentation for usage notes. + + .. versionadded:: 1.4.40 - added :meth:`_engine.FilterResult.yield_per` + so that the method is available on all result set implementations + + .. seealso:: + + :ref:`engine_stream_results` - describes Core behavior for + :meth:`_engine.Result.yield_per` + + :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` + + """ + self._real_result = self._real_result.yield_per(num) + return self + + def _soft_close(self, hard: bool = False) -> None: + self._real_result._soft_close(hard=hard) + + @property + def _soft_closed(self) -> bool: + return self._real_result._soft_closed + + @property + def closed(self) -> bool: + """Return ``True`` if this :class:`_engine.Result` being + proxied by this :class:`_engine.FilterResult` was + **hard closed** by explicitly calling the :meth:`_engine.Result.close` + method. + + This is a direct proxy for the :attr:`_engine.Result.closed` attribute; + see that attribute for details. + + """ + return self._real_result.closed + + def close(self) -> None: + """Close this :class:`_engine.FilterResult`. + + .. versionadded:: 1.4.43 + + """ + self._real_result.close() + + @property + def _attributes(self) -> Dict[Any, Any]: + return self._real_result._attributes + + def _fetchiter_impl(self) -> Iterator[_InterimRowType[Row[Any]]]: + return self._real_result._fetchiter_impl() + + def _fetchone_impl( + self, hard_close: bool = False + ) -> Optional[_InterimRowType[Row[Any]]]: + return self._real_result._fetchone_impl(hard_close=hard_close) + + def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]: + return self._real_result._fetchall_impl() + + def _fetchmany_impl( + self, size: Optional[int] = None + ) -> List[_InterimRowType[Row[Any]]]: + return self._real_result._fetchmany_impl(size=size) + + +class ScalarResult(FilterResult[_R]): + """A wrapper for a :class:`_engine.Result` that returns scalar values + rather than :class:`_row.Row` values. + + The :class:`_engine.ScalarResult` object is acquired by calling the + :meth:`_engine.Result.scalars` method. + + A special limitation of :class:`_engine.ScalarResult` is that it has + no ``fetchone()`` method; since the semantics of ``fetchone()`` are that + the ``None`` value indicates no more results, this is not compatible + with :class:`_engine.ScalarResult` since there is no way to distinguish + between ``None`` as a row value versus ``None`` as an indicator. Use + ``next(result)`` to receive values individually. + + """ + + __slots__ = () + + _generate_rows = False + + _post_creational_filter: Optional[Callable[[Any], Any]] + + def __init__(self, real_result: Result[Any], index: _KeyIndexType): + self._real_result = real_result + + if real_result._source_supports_scalars: + self._metadata = real_result._metadata + self._post_creational_filter = None + else: + self._metadata = real_result._metadata._reduce([index]) + self._post_creational_filter = operator.itemgetter(0) + + self._unique_filter_state = real_result._unique_filter_state + + def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self: + """Apply unique filtering to the objects returned by this + :class:`_engine.ScalarResult`. + + See :meth:`_engine.Result.unique` for usage details. + + """ + self._unique_filter_state = (set(), strategy) + return self + + def partitions(self, size: Optional[int] = None) -> Iterator[Sequence[_R]]: + """Iterate through sub-lists of elements of the size given. + + Equivalent to :meth:`_engine.Result.partitions` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + """ + + getter = self._manyrow_getter + + while True: + partition = getter(self, size) + if partition: + yield partition + else: + break + + def fetchall(self) -> Sequence[_R]: + """A synonym for the :meth:`_engine.ScalarResult.all` method.""" + + return self._allrows() + + def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]: + """Fetch many objects. + + Equivalent to :meth:`_engine.Result.fetchmany` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + """ + return self._manyrow_getter(self, size) + + def all(self) -> Sequence[_R]: + """Return all scalar values in a sequence. + + Equivalent to :meth:`_engine.Result.all` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + """ + return self._allrows() + + def __iter__(self) -> Iterator[_R]: + return self._iter_impl() + + def __next__(self) -> _R: + return self._next_impl() + + def first(self) -> Optional[_R]: + """Fetch the first object or ``None`` if no object is present. + + Equivalent to :meth:`_engine.Result.first` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + + """ + return self._only_one_row( + raise_for_second_row=False, raise_for_none=False, scalar=False + ) + + def one_or_none(self) -> Optional[_R]: + """Return at most one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one_or_none` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=False, scalar=False + ) + + def one(self) -> _R: + """Return exactly one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one` except that + scalar values, rather than :class:`_engine.Row` objects, + are returned. + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=True, scalar=False + ) + + +class TupleResult(FilterResult[_R], util.TypingOnly): + """A :class:`_engine.Result` that's typed as returning plain + Python tuples instead of rows. + + Since :class:`_engine.Row` acts like a tuple in every way already, + this class is a typing only class, regular :class:`_engine.Result` is + still used at runtime. + + """ + + __slots__ = () + + if TYPE_CHECKING: + + def partitions( + self, size: Optional[int] = None + ) -> Iterator[Sequence[_R]]: + """Iterate through sub-lists of elements of the size given. + + Equivalent to :meth:`_engine.Result.partitions` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + """ + ... + + def fetchone(self) -> Optional[_R]: + """Fetch one tuple. + + Equivalent to :meth:`_engine.Result.fetchone` except that + tuple values, rather than :class:`_engine.Row` + objects, are returned. + + """ + ... + + def fetchall(self) -> Sequence[_R]: + """A synonym for the :meth:`_engine.ScalarResult.all` method.""" + ... + + def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]: + """Fetch many objects. + + Equivalent to :meth:`_engine.Result.fetchmany` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + """ + ... + + def all(self) -> Sequence[_R]: # noqa: A001 + """Return all scalar values in a sequence. + + Equivalent to :meth:`_engine.Result.all` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + """ + ... + + def __iter__(self) -> Iterator[_R]: ... + + def __next__(self) -> _R: ... + + def first(self) -> Optional[_R]: + """Fetch the first object or ``None`` if no object is present. + + Equivalent to :meth:`_engine.Result.first` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + + """ + ... + + def one_or_none(self) -> Optional[_R]: + """Return at most one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one_or_none` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + """ + ... + + def one(self) -> _R: + """Return exactly one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one` except that + tuple values, rather than :class:`_engine.Row` objects, + are returned. + + """ + ... + + @overload + def scalar_one(self: TupleResult[Tuple[_T]]) -> _T: ... + + @overload + def scalar_one(self) -> Any: ... + + def scalar_one(self) -> Any: + """Return exactly one scalar result or raise an exception. + + This is equivalent to calling :meth:`_engine.Result.scalars` + and then :meth:`_engine.ScalarResult.one`. + + .. seealso:: + + :meth:`_engine.ScalarResult.one` + + :meth:`_engine.Result.scalars` + + """ + ... + + @overload + def scalar_one_or_none( + self: TupleResult[Tuple[_T]], + ) -> Optional[_T]: ... + + @overload + def scalar_one_or_none(self) -> Optional[Any]: ... + + def scalar_one_or_none(self) -> Optional[Any]: + """Return exactly one or no scalar result. + + This is equivalent to calling :meth:`_engine.Result.scalars` + and then :meth:`_engine.ScalarResult.one_or_none`. + + .. seealso:: + + :meth:`_engine.ScalarResult.one_or_none` + + :meth:`_engine.Result.scalars` + + """ + ... + + @overload + def scalar(self: TupleResult[Tuple[_T]]) -> Optional[_T]: ... + + @overload + def scalar(self) -> Any: ... + + def scalar(self) -> Any: + """Fetch the first column of the first row, and close the result + set. + + Returns ``None`` if there are no rows to fetch. + + No validation is performed to test if additional rows remain. + + After calling this method, the object is fully closed, + e.g. the :meth:`_engine.CursorResult.close` + method will have been called. + + :return: a Python scalar value , or ``None`` if no rows remain. + + """ + ... + + +class MappingResult(_WithKeys, FilterResult[RowMapping]): + """A wrapper for a :class:`_engine.Result` that returns dictionary values + rather than :class:`_engine.Row` values. + + The :class:`_engine.MappingResult` object is acquired by calling the + :meth:`_engine.Result.mappings` method. + + """ + + __slots__ = () + + _generate_rows = True + + _post_creational_filter = operator.attrgetter("_mapping") + + def __init__(self, result: Result[Any]): + self._real_result = result + self._unique_filter_state = result._unique_filter_state + self._metadata = result._metadata + if result._source_supports_scalars: + self._metadata = self._metadata._reduce([0]) + + def unique(self, strategy: Optional[_UniqueFilterType] = None) -> Self: + """Apply unique filtering to the objects returned by this + :class:`_engine.MappingResult`. + + See :meth:`_engine.Result.unique` for usage details. + + """ + self._unique_filter_state = (set(), strategy) + return self + + def columns(self, *col_expressions: _KeyIndexType) -> Self: + """Establish the columns that should be returned in each row.""" + return self._column_slices(col_expressions) + + def partitions( + self, size: Optional[int] = None + ) -> Iterator[Sequence[RowMapping]]: + """Iterate through sub-lists of elements of the size given. + + Equivalent to :meth:`_engine.Result.partitions` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + + getter = self._manyrow_getter + + while True: + partition = getter(self, size) + if partition: + yield partition + else: + break + + def fetchall(self) -> Sequence[RowMapping]: + """A synonym for the :meth:`_engine.MappingResult.all` method.""" + + return self._allrows() + + def fetchone(self) -> Optional[RowMapping]: + """Fetch one object. + + Equivalent to :meth:`_engine.Result.fetchone` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + + row = self._onerow_getter(self) + if row is _NO_ROW: + return None + else: + return row + + def fetchmany(self, size: Optional[int] = None) -> Sequence[RowMapping]: + """Fetch many objects. + + Equivalent to :meth:`_engine.Result.fetchmany` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + + return self._manyrow_getter(self, size) + + def all(self) -> Sequence[RowMapping]: + """Return all scalar values in a sequence. + + Equivalent to :meth:`_engine.Result.all` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + + return self._allrows() + + def __iter__(self) -> Iterator[RowMapping]: + return self._iter_impl() + + def __next__(self) -> RowMapping: + return self._next_impl() + + def first(self) -> Optional[RowMapping]: + """Fetch the first object or ``None`` if no object is present. + + Equivalent to :meth:`_engine.Result.first` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + + """ + return self._only_one_row( + raise_for_second_row=False, raise_for_none=False, scalar=False + ) + + def one_or_none(self) -> Optional[RowMapping]: + """Return at most one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one_or_none` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=False, scalar=False + ) + + def one(self) -> RowMapping: + """Return exactly one object or raise an exception. + + Equivalent to :meth:`_engine.Result.one` except that + :class:`_engine.RowMapping` values, rather than :class:`_engine.Row` + objects, are returned. + + """ + return self._only_one_row( + raise_for_second_row=True, raise_for_none=True, scalar=False + ) + + +class FrozenResult(Generic[_TP]): + """Represents a :class:`_engine.Result` object in a "frozen" state suitable + for caching. + + The :class:`_engine.FrozenResult` object is returned from the + :meth:`_engine.Result.freeze` method of any :class:`_engine.Result` + object. + + A new iterable :class:`_engine.Result` object is generated from a fixed + set of data each time the :class:`_engine.FrozenResult` is invoked as + a callable:: + + + result = connection.execute(query) + + frozen = result.freeze() + + unfrozen_result_one = frozen() + + for row in unfrozen_result_one: + print(row) + + unfrozen_result_two = frozen() + rows = unfrozen_result_two.all() + + # ... etc + + .. versionadded:: 1.4 + + .. seealso:: + + :ref:`do_orm_execute_re_executing` - example usage within the + ORM to implement a result-set cache. + + :func:`_orm.loading.merge_frozen_result` - ORM function to merge + a frozen result back into a :class:`_orm.Session`. + + """ + + data: Sequence[Any] + + def __init__(self, result: Result[_TP]): + self.metadata = result._metadata._for_freeze() + self._source_supports_scalars = result._source_supports_scalars + self._attributes = result._attributes + + if self._source_supports_scalars: + self.data = list(result._raw_row_iterator()) + else: + self.data = result.fetchall() + + def rewrite_rows(self) -> Sequence[Sequence[Any]]: + if self._source_supports_scalars: + return [[elem] for elem in self.data] + else: + return [list(row) for row in self.data] + + def with_new_rows( + self, tuple_data: Sequence[Row[_TP]] + ) -> FrozenResult[_TP]: + fr = FrozenResult.__new__(FrozenResult) + fr.metadata = self.metadata + fr._attributes = self._attributes + fr._source_supports_scalars = self._source_supports_scalars + + if self._source_supports_scalars: + fr.data = [d[0] for d in tuple_data] + else: + fr.data = tuple_data + return fr + + def __call__(self) -> Result[_TP]: + result: IteratorResult[_TP] = IteratorResult( + self.metadata, iter(self.data) + ) + result._attributes = self._attributes + result._source_supports_scalars = self._source_supports_scalars + return result + + +class IteratorResult(Result[_TP]): + """A :class:`_engine.Result` that gets data from a Python iterator of + :class:`_engine.Row` objects or similar row-like data. + + .. versionadded:: 1.4 + + """ + + _hard_closed = False + _soft_closed = False + + def __init__( + self, + cursor_metadata: ResultMetaData, + iterator: Iterator[_InterimSupportsScalarsRowType], + raw: Optional[Result[Any]] = None, + _source_supports_scalars: bool = False, + ): + self._metadata = cursor_metadata + self.iterator = iterator + self.raw = raw + self._source_supports_scalars = _source_supports_scalars + + @property + def closed(self) -> bool: + """Return ``True`` if this :class:`_engine.IteratorResult` was + **hard closed** by explicitly calling the :meth:`_engine.Result.close` + method. + + The attribute is **not** True if the :class:`_engine.Result` was only + **soft closed**; a "soft close" is the style of close that takes place + for example when the :class:`.CursorResult` is returned for a DML + only statement without RETURNING, or when all result rows are fetched. + + .. seealso:: + + :attr:`.CursorResult.returns_rows` - attribute specific to + :class:`.CursorResult` which indicates if the result is one that + may return zero or more rows + + """ + return self._hard_closed + + def _soft_close(self, hard: bool = False, **kw: Any) -> None: + if hard: + self._hard_closed = True + if self.raw is not None: + self.raw._soft_close(hard=hard, **kw) + self.iterator = iter([]) + self._reset_memoizations() + self._soft_closed = True + + def _raise_hard_closed(self) -> NoReturn: + raise exc.ResourceClosedError("This result object is closed.") + + def _raw_row_iterator(self) -> Iterator[_RowData]: + return self.iterator + + def _fetchiter_impl(self) -> Iterator[_InterimSupportsScalarsRowType]: + if self._hard_closed: + self._raise_hard_closed() + return self.iterator + + def _fetchone_impl( + self, hard_close: bool = False + ) -> Optional[_InterimRowType[Row[Any]]]: + if self._hard_closed: + self._raise_hard_closed() + + row = next(self.iterator, _NO_ROW) + if row is _NO_ROW: + self._soft_close(hard=hard_close) + return None + else: + return row + + def _fetchall_impl(self) -> List[_InterimRowType[Row[Any]]]: + if self._hard_closed: + self._raise_hard_closed() + try: + return list(self.iterator) + finally: + self._soft_close() + + def _fetchmany_impl( + self, size: Optional[int] = None + ) -> List[_InterimRowType[Row[Any]]]: + if self._hard_closed: + self._raise_hard_closed() + + return list(itertools.islice(self.iterator, 0, size)) + + +def null_result() -> IteratorResult[Any]: + return IteratorResult(SimpleResultMetaData([]), iter([])) + + +class ChunkedIteratorResult(IteratorResult[_TP]): + """An :class:`_engine.IteratorResult` that works from an + iterator-producing callable. + + The given ``chunks`` argument is a function that is given a number of rows + to return in each chunk, or ``None`` for all rows. The function should + then return an un-consumed iterator of lists, each list of the requested + size. + + The function can be called at any time again, in which case it should + continue from the same result set but adjust the chunk size as given. + + .. versionadded:: 1.4 + + """ + + def __init__( + self, + cursor_metadata: ResultMetaData, + chunks: Callable[ + [Optional[int]], Iterator[Sequence[_InterimRowType[_R]]] + ], + source_supports_scalars: bool = False, + raw: Optional[Result[Any]] = None, + dynamic_yield_per: bool = False, + ): + self._metadata = cursor_metadata + self.chunks = chunks + self._source_supports_scalars = source_supports_scalars + self.raw = raw + self.iterator = itertools.chain.from_iterable(self.chunks(None)) + self.dynamic_yield_per = dynamic_yield_per + + @_generative + def yield_per(self, num: int) -> Self: + # TODO: this throws away the iterator which may be holding + # onto a chunk. the yield_per cannot be changed once any + # rows have been fetched. either find a way to enforce this, + # or we can't use itertools.chain and will instead have to + # keep track. + + self._yield_per = num + self.iterator = itertools.chain.from_iterable(self.chunks(num)) + return self + + def _soft_close(self, hard: bool = False, **kw: Any) -> None: + super()._soft_close(hard=hard, **kw) + self.chunks = lambda size: [] # type: ignore + + def _fetchmany_impl( + self, size: Optional[int] = None + ) -> List[_InterimRowType[Row[Any]]]: + if self.dynamic_yield_per: + self.iterator = itertools.chain.from_iterable(self.chunks(size)) + return super()._fetchmany_impl(size=size) + + +class MergedResult(IteratorResult[_TP]): + """A :class:`_engine.Result` that is merged from any number of + :class:`_engine.Result` objects. + + Returned by the :meth:`_engine.Result.merge` method. + + .. versionadded:: 1.4 + + """ + + closed = False + rowcount: Optional[int] + + def __init__( + self, cursor_metadata: ResultMetaData, results: Sequence[Result[_TP]] + ): + self._results = results + super().__init__( + cursor_metadata, + itertools.chain.from_iterable( + r._raw_row_iterator() for r in results + ), + ) + + self._unique_filter_state = results[0]._unique_filter_state + self._yield_per = results[0]._yield_per + + # going to try something w/ this in next rev + self._source_supports_scalars = results[0]._source_supports_scalars + + self._attributes = self._attributes.merge_with( + *[r._attributes for r in results] + ) + + def _soft_close(self, hard: bool = False, **kw: Any) -> None: + for r in self._results: + r._soft_close(hard=hard, **kw) + if hard: + self.closed = True diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/row.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/row.py new file mode 100644 index 0000000000000000000000000000000000000000..0de3c231cefff5d98c744c233f309688fb97df91 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/row.py @@ -0,0 +1,400 @@ +# engine/row.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Define row constructs including :class:`.Row`.""" + +from __future__ import annotations + +from abc import ABC +import collections.abc as collections_abc +import operator +import typing +from typing import Any +from typing import Callable +from typing import Dict +from typing import Generic +from typing import Iterator +from typing import List +from typing import Mapping +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from ..sql import util as sql_util +from ..util import deprecated +from ..util._has_cy import HAS_CYEXTENSION + +if TYPE_CHECKING or not HAS_CYEXTENSION: + from ._py_row import BaseRow as BaseRow +else: + from sqlalchemy.cyextension.resultproxy import BaseRow as BaseRow + +if TYPE_CHECKING: + from .result import _KeyType + from .result import _ProcessorsType + from .result import RMKeyView + +_T = TypeVar("_T", bound=Any) +_TP = TypeVar("_TP", bound=Tuple[Any, ...]) + + +class Row(BaseRow, Sequence[Any], Generic[_TP]): + """Represent a single result row. + + The :class:`.Row` object represents a row of a database result. It is + typically associated in the 1.x series of SQLAlchemy with the + :class:`_engine.CursorResult` object, however is also used by the ORM for + tuple-like results as of SQLAlchemy 1.4. + + The :class:`.Row` object seeks to act as much like a Python named + tuple as possible. For mapping (i.e. dictionary) behavior on a row, + such as testing for containment of keys, refer to the :attr:`.Row._mapping` + attribute. + + .. seealso:: + + :ref:`tutorial_selecting_data` - includes examples of selecting + rows from SELECT statements. + + .. versionchanged:: 1.4 + + Renamed ``RowProxy`` to :class:`.Row`. :class:`.Row` is no longer a + "proxy" object in that it contains the final form of data within it, + and now acts mostly like a named tuple. Mapping-like functionality is + moved to the :attr:`.Row._mapping` attribute. See + :ref:`change_4710_core` for background on this change. + + """ + + __slots__ = () + + def __setattr__(self, name: str, value: Any) -> NoReturn: + raise AttributeError("can't set attribute") + + def __delattr__(self, name: str) -> NoReturn: + raise AttributeError("can't delete attribute") + + def _tuple(self) -> _TP: + """Return a 'tuple' form of this :class:`.Row`. + + At runtime, this method returns "self"; the :class:`.Row` object is + already a named tuple. However, at the typing level, if this + :class:`.Row` is typed, the "tuple" return type will be a :pep:`484` + ``Tuple`` datatype that contains typing information about individual + elements, supporting typed unpacking and attribute access. + + .. versionadded:: 2.0.19 - The :meth:`.Row._tuple` method supersedes + the previous :meth:`.Row.tuple` method, which is now underscored + to avoid name conflicts with column names in the same way as other + named-tuple methods on :class:`.Row`. + + .. seealso:: + + :attr:`.Row._t` - shorthand attribute notation + + :meth:`.Result.tuples` + + + """ + return self # type: ignore + + @deprecated( + "2.0.19", + "The :meth:`.Row.tuple` method is deprecated in favor of " + ":meth:`.Row._tuple`; all :class:`.Row` " + "methods and library-level attributes are intended to be underscored " + "to avoid name conflicts. Please use :meth:`Row._tuple`.", + ) + def tuple(self) -> _TP: + """Return a 'tuple' form of this :class:`.Row`. + + .. versionadded:: 2.0 + + """ + return self._tuple() + + @property + def _t(self) -> _TP: + """A synonym for :meth:`.Row._tuple`. + + .. versionadded:: 2.0.19 - The :attr:`.Row._t` attribute supersedes + the previous :attr:`.Row.t` attribute, which is now underscored + to avoid name conflicts with column names in the same way as other + named-tuple methods on :class:`.Row`. + + .. seealso:: + + :attr:`.Result.t` + """ + return self # type: ignore + + @property + @deprecated( + "2.0.19", + "The :attr:`.Row.t` attribute is deprecated in favor of " + ":attr:`.Row._t`; all :class:`.Row` " + "methods and library-level attributes are intended to be underscored " + "to avoid name conflicts. Please use :attr:`Row._t`.", + ) + def t(self) -> _TP: + """A synonym for :meth:`.Row._tuple`. + + .. versionadded:: 2.0 + + """ + return self._t + + @property + def _mapping(self) -> RowMapping: + """Return a :class:`.RowMapping` for this :class:`.Row`. + + This object provides a consistent Python mapping (i.e. dictionary) + interface for the data contained within the row. The :class:`.Row` + by itself behaves like a named tuple. + + .. seealso:: + + :attr:`.Row._fields` + + .. versionadded:: 1.4 + + """ + return RowMapping(self._parent, None, self._key_to_index, self._data) + + def _filter_on_values( + self, processor: Optional[_ProcessorsType] + ) -> Row[Any]: + return Row(self._parent, processor, self._key_to_index, self._data) + + if not TYPE_CHECKING: + + def _special_name_accessor(name: str) -> Any: + """Handle ambiguous names such as "count" and "index" """ + + @property + def go(self: Row) -> Any: + if self._parent._has_key(name): + return self.__getattr__(name) + else: + + def meth(*arg: Any, **kw: Any) -> Any: + return getattr(collections_abc.Sequence, name)( + self, *arg, **kw + ) + + return meth + + return go + + count = _special_name_accessor("count") + index = _special_name_accessor("index") + + def __contains__(self, key: Any) -> bool: + return key in self._data + + def _op(self, other: Any, op: Callable[[Any, Any], bool]) -> bool: + return ( + op(self._to_tuple_instance(), other._to_tuple_instance()) + if isinstance(other, Row) + else op(self._to_tuple_instance(), other) + ) + + __hash__ = BaseRow.__hash__ + + if TYPE_CHECKING: + + @overload + def __getitem__(self, index: int) -> Any: ... + + @overload + def __getitem__(self, index: slice) -> Sequence[Any]: ... + + def __getitem__(self, index: Union[int, slice]) -> Any: ... + + def __lt__(self, other: Any) -> bool: + return self._op(other, operator.lt) + + def __le__(self, other: Any) -> bool: + return self._op(other, operator.le) + + def __ge__(self, other: Any) -> bool: + return self._op(other, operator.ge) + + def __gt__(self, other: Any) -> bool: + return self._op(other, operator.gt) + + def __eq__(self, other: Any) -> bool: + return self._op(other, operator.eq) + + def __ne__(self, other: Any) -> bool: + return self._op(other, operator.ne) + + def __repr__(self) -> str: + return repr(sql_util._repr_row(self)) + + @property + def _fields(self) -> Tuple[str, ...]: + """Return a tuple of string keys as represented by this + :class:`.Row`. + + The keys can represent the labels of the columns returned by a core + statement or the names of the orm classes returned by an orm + execution. + + This attribute is analogous to the Python named tuple ``._fields`` + attribute. + + .. versionadded:: 1.4 + + .. seealso:: + + :attr:`.Row._mapping` + + """ + return tuple([k for k in self._parent.keys if k is not None]) + + def _asdict(self) -> Dict[str, Any]: + """Return a new dict which maps field names to their corresponding + values. + + This method is analogous to the Python named tuple ``._asdict()`` + method, and works by applying the ``dict()`` constructor to the + :attr:`.Row._mapping` attribute. + + .. versionadded:: 1.4 + + .. seealso:: + + :attr:`.Row._mapping` + + """ + return dict(self._mapping) + + +BaseRowProxy = BaseRow +RowProxy = Row + + +class ROMappingView(ABC): + __slots__ = () + + _items: Sequence[Any] + _mapping: Mapping["_KeyType", Any] + + def __init__( + self, mapping: Mapping["_KeyType", Any], items: Sequence[Any] + ): + self._mapping = mapping # type: ignore[misc] + self._items = items # type: ignore[misc] + + def __len__(self) -> int: + return len(self._items) + + def __repr__(self) -> str: + return "{0.__class__.__name__}({0._mapping!r})".format(self) + + def __iter__(self) -> Iterator[Any]: + return iter(self._items) + + def __contains__(self, item: Any) -> bool: + return item in self._items + + def __eq__(self, other: Any) -> bool: + return list(other) == list(self) + + def __ne__(self, other: Any) -> bool: + return list(other) != list(self) + + +class ROMappingKeysValuesView( + ROMappingView, typing.KeysView["_KeyType"], typing.ValuesView[Any] +): + __slots__ = ("_items",) # mapping slot is provided by KeysView + + +class ROMappingItemsView(ROMappingView, typing.ItemsView["_KeyType", Any]): + __slots__ = ("_items",) # mapping slot is provided by ItemsView + + +class RowMapping(BaseRow, typing.Mapping["_KeyType", Any]): + """A ``Mapping`` that maps column names and objects to :class:`.Row` + values. + + The :class:`.RowMapping` is available from a :class:`.Row` via the + :attr:`.Row._mapping` attribute, as well as from the iterable interface + provided by the :class:`.MappingResult` object returned by the + :meth:`_engine.Result.mappings` method. + + :class:`.RowMapping` supplies Python mapping (i.e. dictionary) access to + the contents of the row. This includes support for testing of + containment of specific keys (string column names or objects), as well + as iteration of keys, values, and items:: + + for row in result: + if "a" in row._mapping: + print("Column 'a': %s" % row._mapping["a"]) + + print("Column b: %s" % row._mapping[table.c.b]) + + .. versionadded:: 1.4 The :class:`.RowMapping` object replaces the + mapping-like access previously provided by a database result row, + which now seeks to behave mostly like a named tuple. + + """ + + __slots__ = () + + if TYPE_CHECKING: + + def __getitem__(self, key: _KeyType) -> Any: ... + + else: + __getitem__ = BaseRow._get_by_key_impl_mapping + + def _values_impl(self) -> List[Any]: + return list(self._data) + + def __iter__(self) -> Iterator[str]: + return (k for k in self._parent.keys if k is not None) + + def __len__(self) -> int: + return len(self._data) + + def __contains__(self, key: object) -> bool: + return self._parent._has_key(key) + + def __repr__(self) -> str: + return repr(dict(self)) + + def items(self) -> ROMappingItemsView: + """Return a view of key/value tuples for the elements in the + underlying :class:`.Row`. + + """ + return ROMappingItemsView( + self, [(key, self[key]) for key in self.keys()] + ) + + def keys(self) -> RMKeyView: + """Return a view of 'keys' for string column names represented + by the underlying :class:`.Row`. + + """ + + return self._parent.keys + + def values(self) -> ROMappingKeysValuesView: + """Return a view of values for the values represented in the + underlying :class:`.Row`. + + """ + return ROMappingKeysValuesView(self, self._values_impl()) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/strategies.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb06e9443f27863a5b21ef9145c0fcba50020c5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/strategies.py @@ -0,0 +1,16 @@ +# engine/strategies.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Deprecated mock engine strategy used by Alembic.""" + +from __future__ import annotations + +from .mock import MockConnection # noqa + + +class MockEngineStrategy: + MockConnection = MockConnection diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/url.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/url.py new file mode 100644 index 0000000000000000000000000000000000000000..7957eae8e56168c689c050ec61677ff3c67430f9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/url.py @@ -0,0 +1,924 @@ +# engine/url.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Provides 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()``. +""" + +from __future__ import annotations + +import collections.abc as collections_abc +import re +from typing import Any +from typing import cast +from typing import Dict +from typing import Iterable +from typing import List +from typing import Mapping +from typing import NamedTuple +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import Union +from urllib.parse import parse_qsl +from urllib.parse import quote +from urllib.parse import quote_plus +from urllib.parse import unquote + +from .interfaces import Dialect +from .. import exc +from .. import util +from ..dialects import plugins +from ..dialects import registry + + +class URL(NamedTuple): + """ + 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. + + + """ + + drivername: str + """database backend and driver name, such as + ``postgresql+psycopg2`` + + """ + + username: Optional[str] + "username string" + + password: Optional[str] + """password, which is normally a string but may also be any + object that has a ``__str__()`` method.""" + + host: Optional[str] + """hostname or IP number. May also be a data source name for some + drivers.""" + + port: Optional[int] + """integer port number""" + + database: Optional[str] + """database name""" + + query: util.immutabledict[str, Union[Tuple[str, ...], str]] + """an immutable mapping representing the query string. contains strings + for keys and either strings or tuples of strings for values, 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'}) + + To create a mutable copy of this mapping, use the ``dict`` constructor:: + + mutable_query_opts = dict(url.query) + + .. seealso:: + + :attr:`_engine.URL.normalized_query` - normalizes all values into sequences + for consistent processing + + Methods for altering the contents of :attr:`_engine.URL.query`: + + :meth:`_engine.URL.update_query_dict` + + :meth:`_engine.URL.update_query_string` + + :meth:`_engine.URL.update_query_pairs` + + :meth:`_engine.URL.difference_update_query` + + """ # noqa: E501 + + @classmethod + def create( + cls, + drivername: str, + username: Optional[str] = None, + password: Optional[str] = None, + host: Optional[str] = None, + port: Optional[int] = None, + database: Optional[str] = None, + query: Mapping[str, Union[Sequence[str], str]] = util.EMPTY_DICT, + ) -> URL: + """Create 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. + + """ + + return cls( + cls._assert_str(drivername, "drivername"), + cls._assert_none_str(username, "username"), + password, + cls._assert_none_str(host, "host"), + cls._assert_port(port), + cls._assert_none_str(database, "database"), + cls._str_dict(query), + ) + + @classmethod + def _assert_port(cls, port: Optional[int]) -> Optional[int]: + if port is None: + return None + try: + return int(port) + except TypeError: + raise TypeError("Port argument must be an integer or None") + + @classmethod + def _assert_str(cls, v: str, paramname: str) -> str: + if not isinstance(v, str): + raise TypeError("%s must be a string" % paramname) + return v + + @classmethod + def _assert_none_str( + cls, v: Optional[str], paramname: str + ) -> Optional[str]: + if v is None: + return v + + return cls._assert_str(v, paramname) + + @classmethod + def _str_dict( + cls, + dict_: Optional[ + Union[ + Sequence[Tuple[str, Union[Sequence[str], str]]], + Mapping[str, Union[Sequence[str], str]], + ] + ], + ) -> util.immutabledict[str, Union[Tuple[str, ...], str]]: + if dict_ is None: + return util.EMPTY_DICT + + @overload + def _assert_value( + val: str, + ) -> str: ... + + @overload + def _assert_value( + val: Sequence[str], + ) -> Union[str, Tuple[str, ...]]: ... + + def _assert_value( + val: Union[str, Sequence[str]], + ) -> Union[str, Tuple[str, ...]]: + if isinstance(val, str): + return val + elif isinstance(val, collections_abc.Sequence): + return tuple(_assert_value(elem) for elem in val) + else: + raise TypeError( + "Query dictionary values must be strings or " + "sequences of strings" + ) + + def _assert_str(v: str) -> str: + if not isinstance(v, str): + raise TypeError("Query dictionary keys must be strings") + return v + + dict_items: Iterable[Tuple[str, Union[Sequence[str], str]]] + if isinstance(dict_, collections_abc.Sequence): + dict_items = dict_ + else: + dict_items = dict_.items() + + return util.immutabledict( + { + _assert_str(key): _assert_value( + value, + ) + for key, value in dict_items + } + ) + + def set( + self, + drivername: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + host: Optional[str] = None, + port: Optional[int] = None, + database: Optional[str] = None, + query: Optional[Mapping[str, Union[Sequence[str], str]]] = None, + ) -> URL: + """return 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` + + """ + + kw: Dict[str, Any] = {} + if drivername is not None: + kw["drivername"] = drivername + if username is not None: + kw["username"] = username + if password is not None: + kw["password"] = password + if host is not None: + kw["host"] = host + if port is not None: + kw["port"] = port + if database is not None: + kw["database"] = database + if query is not None: + kw["query"] = query + + return self._assert_replace(**kw) + + def _assert_replace(self, **kw: Any) -> URL: + """argument checks before calling _replace()""" + + if "drivername" in kw: + self._assert_str(kw["drivername"], "drivername") + for name in "username", "host", "database": + if name in kw: + self._assert_none_str(kw[name], name) + if "port" in kw: + self._assert_port(kw["port"]) + if "query" in kw: + kw["query"] = self._str_dict(kw["query"]) + + return self._replace(**kw) + + def update_query_string( + self, query_string: str, append: bool = False + ) -> URL: + """Return 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` + + """ # noqa: E501 + return self.update_query_pairs(parse_qsl(query_string), append=append) + + def update_query_pairs( + self, + key_value_pairs: Iterable[Tuple[str, Union[str, List[str]]]], + append: bool = False, + ) -> URL: + """Return 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` + + """ # noqa: E501 + + existing_query = self.query + new_keys: Dict[str, Union[str, List[str]]] = {} + + for key, value in key_value_pairs: + if key in new_keys: + new_keys[key] = util.to_list(new_keys[key]) + cast("List[str]", new_keys[key]).append(cast(str, value)) + else: + new_keys[key] = ( + list(value) if isinstance(value, (list, tuple)) else value + ) + + new_query: Mapping[str, Union[str, Sequence[str]]] + if append: + new_query = {} + + for k in new_keys: + if k in existing_query: + new_query[k] = tuple( + util.to_list(existing_query[k]) + + util.to_list(new_keys[k]) + ) + else: + new_query[k] = new_keys[k] + + new_query.update( + { + k: existing_query[k] + for k in set(existing_query).difference(new_keys) + } + ) + else: + new_query = self.query.union( + { + k: tuple(v) if isinstance(v, list) else v + for k, v in new_keys.items() + } + ) + return self.set(query=new_query) + + def update_query_dict( + self, + query_parameters: Mapping[str, Union[str, List[str]]], + append: bool = False, + ) -> URL: + """Return 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` + + """ # noqa: E501 + return self.update_query_pairs(query_parameters.items(), append=append) + + def difference_update_query(self, names: Iterable[str]) -> URL: + """ + 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` + + """ + + if not set(names).intersection(self.query): + return self + + return URL( + self.drivername, + self.username, + self.password, + self.host, + self.port, + self.database, + util.immutabledict( + { + key: self.query[key] + for key in set(self.query).difference(names) + } + ), + ) + + @property + def normalized_query(self) -> Mapping[str, Sequence[str]]: + """Return 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',)}) + + """ # noqa: E501 + + return util.immutabledict( + { + k: (v,) if not isinstance(v, tuple) else v + for k, v in self.query.items() + } + ) + + @util.deprecated( + "1.4", + "The :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.", + ) + def __to_string__(self, hide_password: bool = True) -> str: + """Render 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. + + """ + return self.render_as_string(hide_password=hide_password) + + def render_as_string(self, hide_password: bool = True) -> str: + """Render this :class:`_engine.URL` object as a string. + + This method is used when the ``__str__()`` or ``__repr__()`` + methods are used. The method directly includes additional options. + + :param hide_password: Defaults to True. The password is not shown + in the string unless this is set to False. + + """ + s = self.drivername + "://" + if self.username is not None: + s += quote(self.username, safe=" +") + if self.password is not None: + s += ":" + ( + "***" + if hide_password + else quote(str(self.password), safe=" +") + ) + s += "@" + if self.host is not None: + if ":" in self.host: + s += f"[{self.host}]" + else: + s += self.host + if self.port is not None: + s += ":" + str(self.port) + if self.database is not None: + s += "/" + self.database + if self.query: + keys = list(self.query) + keys.sort() + s += "?" + "&".join( + f"{quote_plus(k)}={quote_plus(element)}" + for k in keys + for element in util.to_list(self.query[k]) + ) + return s + + def __repr__(self) -> str: + return self.render_as_string() + + def __copy__(self) -> URL: + return self.__class__.create( + self.drivername, + self.username, + self.password, + self.host, + self.port, + self.database, + # note this is an immutabledict of str-> str / tuple of str, + # also fully immutable. does not require deepcopy + self.query, + ) + + def __deepcopy__(self, memo: Any) -> URL: + return self.__copy__() + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: Any) -> bool: + 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 + ) + + def __ne__(self, other: Any) -> bool: + return not self == other + + def get_backend_name(self) -> str: + """Return 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. + + """ + if "+" not in self.drivername: + return self.drivername + else: + return self.drivername.split("+")[0] + + def get_driver_name(self) -> str: + """Return 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. + + """ + + if "+" not in self.drivername: + return self.get_dialect().driver + else: + return self.drivername.split("+")[1] + + def _instantiate_plugins( + self, kwargs: Mapping[str, Any] + ) -> Tuple[URL, List[Any], Dict[str, Any]]: + plugin_names = util.to_list(self.query.get("plugin", ())) + plugin_names += kwargs.get("plugins", []) + + kwargs = dict(kwargs) + + loaded_plugins = [ + plugins.load(plugin_name)(self, kwargs) + for plugin_name in plugin_names + ] + + u = self.difference_update_query(["plugin", "plugins"]) + + for plugin in loaded_plugins: + new_u = plugin.update_url(u) + if new_u is not None: + u = new_u + + kwargs.pop("plugins", None) + + return u, loaded_plugins, kwargs + + def _get_entrypoint(self) -> Type[Dialect]: + """Return 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. + + """ + if "+" not in self.drivername: + name = self.drivername + else: + name = self.drivername.replace("+", ".") + cls = registry.load(name) + # check for legacy dialects that + # would return a module with 'dialect' as the + # actual class + if ( + hasattr(cls, "dialect") + and isinstance(cls.dialect, type) + and issubclass(cls.dialect, Dialect) + ): + return cls.dialect + else: + return cast("Type[Dialect]", cls) + + def get_dialect(self, _is_async: bool = False) -> Type[Dialect]: + """Return the SQLAlchemy :class:`_engine.Dialect` class corresponding + to this URL's driver name. + + """ + entrypoint = self._get_entrypoint() + if _is_async: + dialect_cls = entrypoint.get_async_dialect_cls(self) + else: + dialect_cls = entrypoint.get_dialect_cls(self) + return dialect_cls + + def translate_connect_args( + self, names: Optional[List[str]] = None, **kw: Any + ) -> Dict[str, Any]: + r"""Translate 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. + """ + + if names is not None: + util.warn_deprecated( + "The `URL.translate_connect_args.name`s parameter is " + "deprecated. Please pass the " + "alternate names as kw arguments.", + "1.4", + ) + + translated = {} + attribute_names = ["host", "database", "username", "password", "port"] + for sname in attribute_names: + if names: + name = names.pop(0) + elif sname in kw: + name = kw[sname] + else: + name = sname + if name is not None and getattr(self, sname, False): + if sname == "password": + translated[name] = str(getattr(self, sname)) + else: + translated[name] = getattr(self, sname) + + return translated + + +def make_url(name_or_url: Union[str, URL]) -> URL: + """Given 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` + + """ + + if isinstance(name_or_url, str): + return _parse_url(name_or_url) + elif not isinstance(name_or_url, URL) and not hasattr( + name_or_url, "_sqla_is_testing_if_this_is_a_mock_object" + ): + raise exc.ArgumentError( + f"Expected string or URL object, got {name_or_url!r}" + ) + else: + return name_or_url + + +def _parse_url(name: str) -> URL: + pattern = re.compile( + r""" + (?P[\w\+]+):// + (?: + (?P[^:/]*) + (?::(?P[^@]*))? + @)? + (?: + (?: + \[(?P[^/\?]+)\] | + (?P[^/:\?]+) + )? + (?::(?P[^/\?]*))? + )? + (?:/(?P[^\?]*))? + (?:\?(?P.*))? + """, + re.X, + ) + + m = pattern.match(name) + if m is not None: + components = m.groupdict() + query: Optional[Dict[str, Union[str, List[str]]]] + if components["query"] is not None: + query = {} + + for key, value in parse_qsl(components["query"]): + if key in query: + query[key] = util.to_list(query[key]) + cast("List[str]", query[key]).append(value) + else: + query[key] = value + else: + query = None + components["query"] = query + + if components["username"] is not None: + components["username"] = unquote(components["username"]) + + if components["password"] is not None: + components["password"] = unquote(components["password"]) + + ipv4host = components.pop("ipv4host") + ipv6host = components.pop("ipv6host") + components["host"] = ipv4host or ipv6host + name = components.pop("name") + + if components["port"]: + components["port"] = int(components["port"]) + + return URL.create(name, **components) # type: ignore + + else: + raise exc.ArgumentError( + "Could not parse SQLAlchemy URL from given URL string" + ) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/engine/util.py b/python/user_packages/Python313/site-packages/sqlalchemy/engine/util.py new file mode 100644 index 0000000000000000000000000000000000000000..016d132138b4fc857511e6e44d2acdf5ab515d2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/engine/util.py @@ -0,0 +1,167 @@ +# engine/util.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +import typing +from typing import Any +from typing import Callable +from typing import Optional +from typing import TypeVar + +from .. import exc +from .. import util +from ..util._has_cy import HAS_CYEXTENSION +from ..util.typing import Protocol +from ..util.typing import Self + +if typing.TYPE_CHECKING or not HAS_CYEXTENSION: + from ._py_util import _distill_params_20 as _distill_params_20 + from ._py_util import _distill_raw_params as _distill_raw_params +else: + from sqlalchemy.cyextension.util import ( # noqa: F401 + _distill_params_20 as _distill_params_20, + ) + from sqlalchemy.cyextension.util import ( # noqa: F401 + _distill_raw_params as _distill_raw_params, + ) + +_C = TypeVar("_C", bound=Callable[[], Any]) + + +def connection_memoize(key: str) -> Callable[[_C], _C]: + """Decorator, memoize a function in a connection.info stash. + + Only applicable to functions which take no arguments other than a + connection. The memo will be stored in ``connection.info[key]``. + """ + + @util.decorator + def decorated(fn, self, connection): # type: ignore + connection = connection.connect() + try: + return connection.info[key] + except KeyError: + connection.info[key] = val = fn(self, connection) + return val + + return decorated + + +class _TConsSubject(Protocol): + _trans_context_manager: Optional[TransactionalContext] + + +class TransactionalContext: + """Apply Python context manager behavior to transaction objects. + + Performs validation to ensure the subject of the transaction is not + used if the transaction were ended prematurely. + + """ + + __slots__ = ("_outer_trans_ctx", "_trans_subject", "__weakref__") + + _trans_subject: Optional[_TConsSubject] + + def _transaction_is_active(self) -> bool: + raise NotImplementedError() + + def _transaction_is_closed(self) -> bool: + raise NotImplementedError() + + def _rollback_can_be_called(self) -> bool: + """indicates the object is in a state that is known to be acceptable + for rollback() to be called. + + This does not necessarily mean rollback() will succeed or not raise + an error, just that there is currently no state detected that indicates + rollback() would fail or emit warnings. + + It also does not mean that there's a transaction in progress, as + it is usually safe to call rollback() even if no transaction is + present. + + .. versionadded:: 1.4.28 + + """ + raise NotImplementedError() + + def _get_subject(self) -> _TConsSubject: + raise NotImplementedError() + + def commit(self) -> None: + raise NotImplementedError() + + def rollback(self) -> None: + raise NotImplementedError() + + def close(self) -> None: + raise NotImplementedError() + + @classmethod + def _trans_ctx_check(cls, subject: _TConsSubject) -> None: + trans_context = subject._trans_context_manager + if trans_context: + if not trans_context._transaction_is_active(): + raise exc.InvalidRequestError( + "Can't operate on closed transaction inside context " + "manager. Please complete the context manager " + "before emitting further commands." + ) + + def __enter__(self) -> Self: + subject = self._get_subject() + + # none for outer transaction, may be non-None for nested + # savepoint, legacy nesting cases + trans_context = subject._trans_context_manager + self._outer_trans_ctx = trans_context + + self._trans_subject = subject + subject._trans_context_manager = self + return self + + def __exit__(self, type_: Any, value: Any, traceback: Any) -> None: + subject = getattr(self, "_trans_subject", None) + + # simplistically we could assume that + # "subject._trans_context_manager is self". However, any calling + # code that is manipulating __exit__ directly would break this + # assumption. alembic context manager + # is an example of partial use that just calls __exit__ and + # not __enter__ at the moment. it's safe to assume this is being done + # in the wild also + out_of_band_exit = ( + subject is None or subject._trans_context_manager is not self + ) + + if type_ is None and self._transaction_is_active(): + try: + self.commit() + except: + with util.safe_reraise(): + if self._rollback_can_be_called(): + self.rollback() + finally: + if not out_of_band_exit: + assert subject is not None + subject._trans_context_manager = self._outer_trans_ctx + self._trans_subject = self._outer_trans_ctx = None + else: + try: + if not self._transaction_is_active(): + if not self._transaction_is_closed(): + self.close() + else: + if self._rollback_can_be_called(): + self.rollback() + finally: + if not out_of_band_exit: + assert subject is not None + subject._trans_context_manager = self._outer_trans_ctx + self._trans_subject = self._outer_trans_ctx = None diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a6dec06339f7e7ae1b8dc8791cf8c7c4b952b8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/__init__.py @@ -0,0 +1,26 @@ +# event/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +from .api import CANCEL as CANCEL +from .api import contains as contains +from .api import listen as listen +from .api import listens_for as listens_for +from .api import NO_RETVAL as NO_RETVAL +from .api import remove as remove +from .attr import _InstanceLevelDispatch as _InstanceLevelDispatch +from .attr import RefCollection as RefCollection +from .base import _Dispatch as _Dispatch +from .base import _DispatchCommon as _DispatchCommon +from .base import dispatcher as dispatcher +from .base import Events as Events +from .legacy import _legacy_signature as _legacy_signature +from .legacy import _omit_standard_example as _omit_standard_example +from .registry import _EventKey as _EventKey +from .registry import _ListenerFnType as _ListenerFnType +from .registry import EventTarget as EventTarget diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/api.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/api.py new file mode 100644 index 0000000000000000000000000000000000000000..97deaa09c18ebb8507e46e06d4b30887adf5bb2a --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/api.py @@ -0,0 +1,220 @@ +# event/api.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Public API functions for the event system.""" +from __future__ import annotations + +from typing import Any +from typing import Callable + +from .base import _registrars +from .registry import _ET +from .registry import _EventKey +from .registry import _ListenerFnType +from .. import exc +from .. import util + + +CANCEL = util.symbol("CANCEL") +NO_RETVAL = util.symbol("NO_RETVAL") + + +def _event_key( + target: _ET, identifier: str, fn: _ListenerFnType +) -> _EventKey[_ET]: + for evt_cls in _registrars[identifier]: + tgt = evt_cls._accept_with(target, identifier) + if tgt is not None: + return _EventKey(target, identifier, fn, tgt) + else: + raise exc.InvalidRequestError( + "No such event '%s' for target '%s'" % (identifier, target) + ) + + +def listen( + target: Any, identifier: str, fn: Callable[..., Any], *args: Any, **kw: Any +) -> None: + """Register a listener function for the given target. + + The :func:`.listen` function is part of the primary interface for the + SQLAlchemy event system, documented at :ref:`event_toplevel`. + + e.g.:: + + from sqlalchemy import event + from sqlalchemy.schema import UniqueConstraint + + + def unique_constraint_name(const, table): + const.name = "uq_%s_%s" % (table.name, list(const.columns)[0].name) + + + event.listen( + UniqueConstraint, "after_parent_attach", unique_constraint_name + ) + + :param bool insert: The default behavior for event handlers is to append + the decorated user defined function to an internal list of registered + event listeners upon discovery. If a user registers a function with + ``insert=True``, SQLAlchemy will insert (prepend) the function to the + internal list upon discovery. This feature is not typically used or + recommended by the SQLAlchemy maintainers, but is provided to ensure + certain user defined functions can run before others, such as when + :ref:`Changing the sql_mode in MySQL `. + + :param bool named: When using named argument passing, the names listed in + the function argument specification will be used as keys in the + dictionary. + See :ref:`event_named_argument_styles`. + + :param bool once: Private/Internal API usage. Deprecated. This parameter + would provide that an event function would run only once per given + target. It does not however imply automatic de-registration of the + listener function; associating an arbitrarily high number of listeners + without explicitly removing them will cause memory to grow unbounded even + if ``once=True`` is specified. + + :param bool propagate: The ``propagate`` kwarg is available when working + with ORM instrumentation and mapping events. + See :class:`_ormevent.MapperEvents` and + :meth:`_ormevent.MapperEvents.before_mapper_configured` for examples. + + :param bool retval: This flag applies only to specific event listeners, + each of which includes documentation explaining when it should be used. + By default, no listener ever requires a return value. + However, some listeners do support special behaviors for return values, + and include in their documentation that the ``retval=True`` flag is + necessary for a return value to be processed. + + Event listener suites that make use of :paramref:`_event.listen.retval` + include :class:`_events.ConnectionEvents` and + :class:`_ormevent.AttributeEvents`. + + .. note:: + + The :func:`.listen` function cannot be called at the same time + that the target event is being run. This has implications + for thread safety, and also means an event cannot be added + from inside the listener function for itself. The list of + events to be run are present inside of a mutable collection + that can't be changed during iteration. + + Event registration and removal is not intended to be a "high + velocity" operation; it is a configurational operation. For + systems that need to quickly associate and deassociate with + events at high scale, use a mutable structure that is handled + from inside of a single listener. + + .. seealso:: + + :func:`.listens_for` + + :func:`.remove` + + """ + + _event_key(target, identifier, fn).listen(*args, **kw) + + +def listens_for( + target: Any, identifier: str, *args: Any, **kw: Any +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + """Decorate a function as a listener for the given target + identifier. + + The :func:`.listens_for` decorator is part of the primary interface for the + SQLAlchemy event system, documented at :ref:`event_toplevel`. + + This function generally shares the same kwargs as :func:`.listen`. + + e.g.:: + + from sqlalchemy import event + from sqlalchemy.schema import UniqueConstraint + + + @event.listens_for(UniqueConstraint, "after_parent_attach") + def unique_constraint_name(const, table): + const.name = "uq_%s_%s" % (table.name, list(const.columns)[0].name) + + A given function can also be invoked for only the first invocation + of the event using the ``once`` argument:: + + @event.listens_for(Mapper, "before_configure", once=True) + def on_config(): + do_config() + + .. warning:: The ``once`` argument does not imply automatic de-registration + of the listener function after it has been invoked a first time; a + listener entry will remain associated with the target object. + Associating an arbitrarily high number of listeners without explicitly + removing them will cause memory to grow unbounded even if ``once=True`` + is specified. + + .. seealso:: + + :func:`.listen` - general description of event listening + + """ + + def decorate(fn: Callable[..., Any]) -> Callable[..., Any]: + listen(target, identifier, fn, *args, **kw) + return fn + + return decorate + + +def remove(target: Any, identifier: str, fn: Callable[..., Any]) -> None: + """Remove an event listener. + + The arguments here should match exactly those which were sent to + :func:`.listen`; all the event registration which proceeded as a result + of this call will be reverted by calling :func:`.remove` with the same + arguments. + + e.g.:: + + # if a function was registered like this... + @event.listens_for(SomeMappedClass, "before_insert", propagate=True) + def my_listener_function(*arg): + pass + + + # ... it's removed like this + event.remove(SomeMappedClass, "before_insert", my_listener_function) + + Above, the listener function associated with ``SomeMappedClass`` was also + propagated to subclasses of ``SomeMappedClass``; the :func:`.remove` + function will revert all of these operations. + + .. note:: + + The :func:`.remove` function cannot be called at the same time + that the target event is being run. This has implications + for thread safety, and also means an event cannot be removed + from inside the listener function for itself. The list of + events to be run are present inside of a mutable collection + that can't be changed during iteration. + + Event registration and removal is not intended to be a "high + velocity" operation; it is a configurational operation. For + systems that need to quickly associate and deassociate with + events at high scale, use a mutable structure that is handled + from inside of a single listener. + + .. seealso:: + + :func:`.listen` + + """ + _event_key(target, identifier, fn).remove() + + +def contains(target: Any, identifier: str, fn: Callable[..., Any]) -> bool: + """Return True if the given target/ident/fn is set up to listen.""" + + return _event_key(target, identifier, fn).contains() diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/attr.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/attr.py new file mode 100644 index 0000000000000000000000000000000000000000..d9975948bd9fc545dc24ef838f7b5f2f205d323b --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/attr.py @@ -0,0 +1,676 @@ +# event/attr.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Attribute implementation for _Dispatch classes. + +The various listener targets for a particular event class are represented +as attributes, which refer to collections of listeners to be fired off. +These collections can exist at the class level as well as at the instance +level. An event is fired off using code like this:: + + some_object.dispatch.first_connect(arg1, arg2) + +Above, ``some_object.dispatch`` would be an instance of ``_Dispatch`` and +``first_connect`` is typically an instance of ``_ListenerCollection`` +if event listeners are present, or ``_EmptyListener`` if none are present. + +The attribute mechanics here spend effort trying to ensure listener functions +are available with a minimum of function call overhead, that unnecessary +objects aren't created (i.e. many empty per-instance listener collections), +as well as that everything is garbage collectable when owning references are +lost. Other features such as "propagation" of listener functions across +many ``_Dispatch`` instances, "joining" of multiple ``_Dispatch`` instances, +as well as support for subclass propagation (e.g. events assigned to +``Pool`` vs. ``QueuePool``) are all implemented here. + +""" +from __future__ import annotations + +import collections +from itertools import chain +import threading +from types import TracebackType +import typing +from typing import Any +from typing import cast +from typing import Collection +from typing import Deque +from typing import FrozenSet +from typing import Generic +from typing import Iterator +from typing import MutableMapping +from typing import MutableSequence +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TypeVar +from typing import Union +import weakref + +from . import legacy +from . import registry +from .registry import _ET +from .registry import _EventKey +from .registry import _ListenerFnType +from .. import exc +from .. import util +from ..util.concurrency import AsyncAdaptedLock +from ..util.typing import Protocol + +_T = TypeVar("_T", bound=Any) + +if typing.TYPE_CHECKING: + from .base import _Dispatch + from .base import _DispatchCommon + from .base import _HasEventsDispatch + + +class RefCollection(util.MemoizedSlots, Generic[_ET]): + __slots__ = ("ref",) + + ref: weakref.ref[RefCollection[_ET]] + + def _memoized_attr_ref(self) -> weakref.ref[RefCollection[_ET]]: + return weakref.ref(self, registry._collection_gced) + + +class _empty_collection(Collection[_T]): + def append(self, element: _T) -> None: + pass + + def appendleft(self, element: _T) -> None: + pass + + def extend(self, other: Sequence[_T]) -> None: + pass + + def remove(self, element: _T) -> None: + pass + + def __contains__(self, element: Any) -> bool: + return False + + def __iter__(self) -> Iterator[_T]: + return iter([]) + + def clear(self) -> None: + pass + + def __len__(self) -> int: + return 0 + + +_ListenerFnSequenceType = Union[Deque[_T], _empty_collection[_T]] + + +class _ClsLevelDispatch(RefCollection[_ET]): + """Class-level events on :class:`._Dispatch` classes.""" + + __slots__ = ( + "clsname", + "name", + "arg_names", + "has_kw", + "legacy_signatures", + "_clslevel", + "__weakref__", + ) + + clsname: str + name: str + arg_names: Sequence[str] + has_kw: bool + legacy_signatures: MutableSequence[legacy._LegacySignatureType] + _clslevel: MutableMapping[ + Type[_ET], _ListenerFnSequenceType[_ListenerFnType] + ] + + def __init__( + self, + parent_dispatch_cls: Type[_HasEventsDispatch[_ET]], + fn: _ListenerFnType, + ): + self.name = fn.__name__ + self.clsname = parent_dispatch_cls.__name__ + argspec = util.inspect_getfullargspec(fn) + self.arg_names = argspec.args[1:] + self.has_kw = bool(argspec.varkw) + self.legacy_signatures = list( + reversed( + sorted( + getattr(fn, "_legacy_signatures", []), key=lambda s: s[0] + ) + ) + ) + fn.__doc__ = legacy._augment_fn_docs(self, parent_dispatch_cls, fn) + + self._clslevel = weakref.WeakKeyDictionary() + + def _adjust_fn_spec( + self, fn: _ListenerFnType, named: bool + ) -> _ListenerFnType: + if named: + fn = self._wrap_fn_for_kw(fn) + if self.legacy_signatures: + try: + argspec = util.get_callable_argspec(fn, no_self=True) + except TypeError: + pass + else: + fn = legacy._wrap_fn_for_legacy(self, fn, argspec) + return fn + + def _wrap_fn_for_kw(self, fn: _ListenerFnType) -> _ListenerFnType: + def wrap_kw(*args: Any, **kw: Any) -> Any: + argdict = dict(zip(self.arg_names, args)) + argdict.update(kw) + return fn(**argdict) + + return wrap_kw + + def _do_insert_or_append( + self, event_key: _EventKey[_ET], is_append: bool + ) -> None: + target = event_key.dispatch_target + assert isinstance( + target, type + ), "Class-level Event targets must be classes." + if not getattr(target, "_sa_propagate_class_events", True): + raise exc.InvalidRequestError( + f"Can't assign an event directly to the {target} class" + ) + + cls: Type[_ET] + + for cls in util.walk_subclasses(target): + if cls is not target and cls not in self._clslevel: + self.update_subclass(cls) + else: + if cls not in self._clslevel: + self.update_subclass(cls) + if is_append: + self._clslevel[cls].append(event_key._listen_fn) + else: + self._clslevel[cls].appendleft(event_key._listen_fn) + registry._stored_in_collection(event_key, self) + + def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None: + self._do_insert_or_append(event_key, is_append=False) + + def append(self, event_key: _EventKey[_ET], propagate: bool) -> None: + self._do_insert_or_append(event_key, is_append=True) + + def update_subclass(self, target: Type[_ET]) -> None: + if target not in self._clslevel: + if getattr(target, "_sa_propagate_class_events", True): + self._clslevel[target] = collections.deque() + else: + self._clslevel[target] = _empty_collection() + + clslevel = self._clslevel[target] + cls: Type[_ET] + for cls in target.__mro__[1:]: + if cls in self._clslevel: + clslevel.extend( + [fn for fn in self._clslevel[cls] if fn not in clslevel] + ) + + def remove(self, event_key: _EventKey[_ET]) -> None: + target = event_key.dispatch_target + cls: Type[_ET] + for cls in util.walk_subclasses(target): + if cls in self._clslevel: + self._clslevel[cls].remove(event_key._listen_fn) + registry._removed_from_collection(event_key, self) + + def clear(self) -> None: + """Clear all class level listeners""" + + to_clear: Set[_ListenerFnType] = set() + for dispatcher in self._clslevel.values(): + to_clear.update(dispatcher) + dispatcher.clear() + registry._clear(self, to_clear) + + def for_modify(self, obj: _Dispatch[_ET]) -> _ClsLevelDispatch[_ET]: + """Return an event collection which can be modified. + + For _ClsLevelDispatch at the class level of + a dispatcher, this returns self. + + """ + return self + + +class _InstanceLevelDispatch(RefCollection[_ET], Collection[_ListenerFnType]): + __slots__ = () + + parent: _ClsLevelDispatch[_ET] + + def _adjust_fn_spec( + self, fn: _ListenerFnType, named: bool + ) -> _ListenerFnType: + return self.parent._adjust_fn_spec(fn, named) + + def __contains__(self, item: Any) -> bool: + raise NotImplementedError() + + def __len__(self) -> int: + raise NotImplementedError() + + def __iter__(self) -> Iterator[_ListenerFnType]: + raise NotImplementedError() + + def __bool__(self) -> bool: + raise NotImplementedError() + + def exec_once(self, *args: Any, **kw: Any) -> None: + raise NotImplementedError() + + def exec_once_unless_exception(self, *args: Any, **kw: Any) -> None: + raise NotImplementedError() + + def _exec_w_sync_on_first_run(self, *args: Any, **kw: Any) -> None: + raise NotImplementedError() + + def __call__(self, *args: Any, **kw: Any) -> None: + raise NotImplementedError() + + def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None: + raise NotImplementedError() + + def append(self, event_key: _EventKey[_ET], propagate: bool) -> None: + raise NotImplementedError() + + def remove(self, event_key: _EventKey[_ET]) -> None: + raise NotImplementedError() + + def for_modify( + self, obj: _DispatchCommon[_ET] + ) -> _InstanceLevelDispatch[_ET]: + """Return an event collection which can be modified. + + For _ClsLevelDispatch at the class level of + a dispatcher, this returns self. + + """ + return self + + +class _EmptyListener(_InstanceLevelDispatch[_ET]): + """Serves as a proxy interface to the events + served by a _ClsLevelDispatch, when there are no + instance-level events present. + + Is replaced by _ListenerCollection when instance-level + events are added. + + """ + + __slots__ = "parent", "parent_listeners", "name" + + propagate: FrozenSet[_ListenerFnType] = frozenset() + listeners: Tuple[()] = () + parent: _ClsLevelDispatch[_ET] + parent_listeners: _ListenerFnSequenceType[_ListenerFnType] + name: str + + def __init__(self, parent: _ClsLevelDispatch[_ET], target_cls: Type[_ET]): + if target_cls not in parent._clslevel: + parent.update_subclass(target_cls) + self.parent = parent + self.parent_listeners = parent._clslevel[target_cls] + self.name = parent.name + + def for_modify( + self, obj: _DispatchCommon[_ET] + ) -> _ListenerCollection[_ET]: + """Return an event collection which can be modified. + + For _EmptyListener at the instance level of + a dispatcher, this generates a new + _ListenerCollection, applies it to the instance, + and returns it. + + """ + obj = cast("_Dispatch[_ET]", obj) + + assert obj._instance_cls is not None + existing = getattr(obj, self.name) + + with util.mini_gil: + if existing is self or isinstance(existing, _JoinedListener): + result = _ListenerCollection(self.parent, obj._instance_cls) + else: + # this codepath is an extremely rare race condition + # that has been observed in test_pool.py->test_timeout_race + # with freethreaded. + assert isinstance(existing, _ListenerCollection) + return existing + + if existing is self: + setattr(obj, self.name, result) + return result + + def _needs_modify(self, *args: Any, **kw: Any) -> NoReturn: + raise NotImplementedError("need to call for_modify()") + + def exec_once(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def exec_once_unless_exception(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def insert(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def append(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def remove(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def clear(self, *args: Any, **kw: Any) -> NoReturn: + self._needs_modify(*args, **kw) + + def __call__(self, *args: Any, **kw: Any) -> None: + """Execute this event.""" + + for fn in self.parent_listeners: + fn(*args, **kw) + + def __contains__(self, item: Any) -> bool: + return item in self.parent_listeners + + def __len__(self) -> int: + return len(self.parent_listeners) + + def __iter__(self) -> Iterator[_ListenerFnType]: + return iter(self.parent_listeners) + + def __bool__(self) -> bool: + return bool(self.parent_listeners) + + +class _MutexProtocol(Protocol): + def __enter__(self) -> bool: ... + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: ... + + +class _CompoundListener(_InstanceLevelDispatch[_ET]): + __slots__ = ( + "_exec_once_mutex", + "_exec_once", + "_exec_w_sync_once", + "_is_asyncio", + ) + + _exec_once_mutex: Optional[_MutexProtocol] + parent_listeners: Collection[_ListenerFnType] + listeners: Collection[_ListenerFnType] + _exec_once: bool + _exec_w_sync_once: bool + + def __init__(self, *arg: Any, **kw: Any): + super().__init__(*arg, **kw) + self._is_asyncio = False + + def _set_asyncio(self) -> None: + self._is_asyncio = True + + def _get_exec_once_mutex(self) -> _MutexProtocol: + with util.mini_gil: + if self._exec_once_mutex is not None: + return self._exec_once_mutex + + if self._is_asyncio: + mutex = AsyncAdaptedLock() + else: + mutex = threading.Lock() # type: ignore[assignment] + self._exec_once_mutex = mutex + + return mutex + + def _exec_once_impl( + self, retry_on_exception: bool, *args: Any, **kw: Any + ) -> None: + with self._get_exec_once_mutex(): + if not self._exec_once: + try: + self(*args, **kw) + exception = False + except: + exception = True + raise + finally: + if not exception or not retry_on_exception: + self._exec_once = True + + def exec_once(self, *args: Any, **kw: Any) -> None: + """Execute this event, but only if it has not been + executed already for this collection.""" + + if not self._exec_once: + self._exec_once_impl(False, *args, **kw) + + def exec_once_unless_exception(self, *args: Any, **kw: Any) -> None: + """Execute this event, but only if it has not been + executed already for this collection, or was called + by a previous exec_once_unless_exception call and + raised an exception. + + If exec_once was already called, then this method will never run + the callable regardless of whether it raised or not. + + .. versionadded:: 1.3.8 + + """ + if not self._exec_once: + self._exec_once_impl(True, *args, **kw) + + def _exec_w_sync_on_first_run(self, *args: Any, **kw: Any) -> None: + """Execute this event, and use a mutex if it has not been + executed already for this collection, or was called + by a previous _exec_w_sync_on_first_run call and + raised an exception. + + If _exec_w_sync_on_first_run was already called and didn't raise an + exception, then a mutex is not used. It's not guaranteed + the mutex won't be used more than once in the case of very rare + race conditions. + + .. versionadded:: 1.4.11 + + """ + if not self._exec_w_sync_once: + with self._get_exec_once_mutex(): + try: + self(*args, **kw) + except: + raise + else: + self._exec_w_sync_once = True + else: + self(*args, **kw) + + def __call__(self, *args: Any, **kw: Any) -> None: + """Execute this event.""" + + for fn in self.parent_listeners: + fn(*args, **kw) + for fn in self.listeners: + fn(*args, **kw) + + def __contains__(self, item: Any) -> bool: + return item in self.parent_listeners or item in self.listeners + + def __len__(self) -> int: + return len(self.parent_listeners) + len(self.listeners) + + def __iter__(self) -> Iterator[_ListenerFnType]: + return chain(self.parent_listeners, self.listeners) + + def __bool__(self) -> bool: + return bool(self.listeners or self.parent_listeners) + + +class _ListenerCollection(_CompoundListener[_ET]): + """Instance-level attributes on instances of :class:`._Dispatch`. + + Represents a collection of listeners. + + As of 0.7.9, _ListenerCollection is only first + created via the _EmptyListener.for_modify() method. + + """ + + __slots__ = ( + "parent_listeners", + "parent", + "name", + "listeners", + "propagate", + "__weakref__", + ) + + parent_listeners: Collection[_ListenerFnType] + parent: _ClsLevelDispatch[_ET] + name: str + listeners: Deque[_ListenerFnType] + propagate: Set[_ListenerFnType] + + def __init__(self, parent: _ClsLevelDispatch[_ET], target_cls: Type[_ET]): + super().__init__() + if target_cls not in parent._clslevel: + parent.update_subclass(target_cls) + self._exec_once = False + self._exec_w_sync_once = False + self._exec_once_mutex = None + self.parent_listeners = parent._clslevel[target_cls] + self.parent = parent + self.name = parent.name + self.listeners = collections.deque() + self.propagate = set() + + def for_modify( + self, obj: _DispatchCommon[_ET] + ) -> _ListenerCollection[_ET]: + """Return an event collection which can be modified. + + For _ListenerCollection at the instance level of + a dispatcher, this returns self. + + """ + return self + + def _update( + self, other: _ListenerCollection[_ET], only_propagate: bool = True + ) -> None: + """Populate from the listeners in another :class:`_Dispatch` + object.""" + existing_listeners = self.listeners + existing_listener_set = set(existing_listeners) + self.propagate.update(other.propagate) + other_listeners = [ + l + for l in other.listeners + if l not in existing_listener_set + and not only_propagate + or l in self.propagate + ] + + existing_listeners.extend(other_listeners) + + if other._is_asyncio: + self._set_asyncio() + + to_associate = other.propagate.union(other_listeners) + registry._stored_in_collection_multi(self, other, to_associate) + + def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None: + if event_key.prepend_to_list(self, self.listeners): + if propagate: + self.propagate.add(event_key._listen_fn) + + def append(self, event_key: _EventKey[_ET], propagate: bool) -> None: + if event_key.append_to_list(self, self.listeners): + if propagate: + self.propagate.add(event_key._listen_fn) + + def remove(self, event_key: _EventKey[_ET]) -> None: + self.listeners.remove(event_key._listen_fn) + self.propagate.discard(event_key._listen_fn) + registry._removed_from_collection(event_key, self) + + def clear(self) -> None: + registry._clear(self, self.listeners) + self.propagate.clear() + self.listeners.clear() + + +class _JoinedListener(_CompoundListener[_ET]): + __slots__ = "parent_dispatch", "name", "local", "parent_listeners" + + parent_dispatch: _DispatchCommon[_ET] + name: str + local: _InstanceLevelDispatch[_ET] + parent_listeners: Collection[_ListenerFnType] + + def __init__( + self, + parent_dispatch: _DispatchCommon[_ET], + name: str, + local: _EmptyListener[_ET], + ): + self._exec_once = False + self._exec_w_sync_once = False + self._exec_once_mutex = None + self.parent_dispatch = parent_dispatch + self.name = name + self.local = local + self.parent_listeners = self.local + + if not typing.TYPE_CHECKING: + # first error, I don't really understand: + # Signature of "listeners" incompatible with + # supertype "_CompoundListener" [override] + # the name / return type are exactly the same + # second error is getattr_isn't typed, the cast() here + # adds too much method overhead + @property + def listeners(self) -> Collection[_ListenerFnType]: + return getattr(self.parent_dispatch, self.name) + + def _adjust_fn_spec( + self, fn: _ListenerFnType, named: bool + ) -> _ListenerFnType: + return self.local._adjust_fn_spec(fn, named) + + def for_modify(self, obj: _DispatchCommon[_ET]) -> _JoinedListener[_ET]: + self.local = self.parent_listeners = self.local.for_modify(obj) + return self + + def insert(self, event_key: _EventKey[_ET], propagate: bool) -> None: + self.local.insert(event_key, propagate) + + def append(self, event_key: _EventKey[_ET], propagate: bool) -> None: + self.local.append(event_key, propagate) + + def remove(self, event_key: _EventKey[_ET]) -> None: + self.local.remove(event_key) + + def clear(self) -> None: + raise NotImplementedError() diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/base.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6bc00d9c967b69b328d7e4e76f94d3b8854c27 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/base.py @@ -0,0 +1,472 @@ +# event/base.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Base implementation classes. + +The public-facing ``Events`` serves as the base class for an event interface; +its public attributes represent different kinds of events. These attributes +are mirrored onto a ``_Dispatch`` class, which serves as a container for +collections of listener functions. These collections are represented both +at the class level of a particular ``_Dispatch`` class as well as within +instances of ``_Dispatch``. + +""" +from __future__ import annotations + +import typing +from typing import Any +from typing import cast +from typing import Dict +from typing import Generic +from typing import Iterator +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import Optional +from typing import overload +from typing import Tuple +from typing import Type +from typing import Union +import weakref + +from .attr import _ClsLevelDispatch +from .attr import _EmptyListener +from .attr import _InstanceLevelDispatch +from .attr import _JoinedListener +from .registry import _ET +from .registry import _EventKey +from .. import util +from ..util.typing import Literal + +_registrars: MutableMapping[str, List[Type[_HasEventsDispatch[Any]]]] = ( + util.defaultdict(list) +) + + +def _is_event_name(name: str) -> bool: + # _sa_event prefix is special to support internal-only event names. + # most event names are just plain method names that aren't + # underscored. + + return ( + not name.startswith("_") and name != "dispatch" + ) or name.startswith("_sa_event") + + +class _UnpickleDispatch: + """Serializable callable that re-generates an instance of + :class:`_Dispatch` given a particular :class:`.Events` subclass. + + """ + + def __call__(self, _instance_cls: Type[_ET]) -> _Dispatch[_ET]: + for cls in _instance_cls.__mro__: + if "dispatch" in cls.__dict__: + return cast( + "_Dispatch[_ET]", cls.__dict__["dispatch"].dispatch + )._for_class(_instance_cls) + else: + raise AttributeError("No class with a 'dispatch' member present.") + + +class _DispatchCommon(Generic[_ET]): + __slots__ = () + + _instance_cls: Optional[Type[_ET]] + + def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]: + raise NotImplementedError() + + def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]: + raise NotImplementedError() + + @property + def _events(self) -> Type[_HasEventsDispatch[_ET]]: + raise NotImplementedError() + + +class _Dispatch(_DispatchCommon[_ET]): + """Mirror the event listening definitions of an Events class with + listener collections. + + Classes which define a "dispatch" member will return a + non-instantiated :class:`._Dispatch` subclass when the member + is accessed at the class level. When the "dispatch" member is + accessed at the instance level of its owner, an instance + of the :class:`._Dispatch` class is returned. + + A :class:`._Dispatch` class is generated for each :class:`.Events` + class defined, by the :meth:`._HasEventsDispatch._create_dispatcher_class` + method. The original :class:`.Events` classes remain untouched. + This decouples the construction of :class:`.Events` subclasses from + the implementation used by the event internals, and allows + inspecting tools like Sphinx to work in an unsurprising + way against the public API. + + """ + + # "active_history" is an ORM case we add here. ideally a better + # system would be in place for ad-hoc attributes. + __slots__ = "_parent", "_instance_cls", "__dict__", "_empty_listeners" + + _active_history: bool + + _empty_listener_reg: MutableMapping[ + Type[_ET], Dict[str, _EmptyListener[_ET]] + ] = weakref.WeakKeyDictionary() + + _empty_listeners: Dict[str, _EmptyListener[_ET]] + + _event_names: List[str] + + _instance_cls: Optional[Type[_ET]] + + _joined_dispatch_cls: Type[_JoinedDispatcher[_ET]] + + _events: Type[_HasEventsDispatch[_ET]] + """reference back to the Events class. + + Bidirectional against _HasEventsDispatch.dispatch + + """ + + def __init__( + self, + parent: Optional[_Dispatch[_ET]], + instance_cls: Optional[Type[_ET]] = None, + ): + self._parent = parent + self._instance_cls = instance_cls + + if instance_cls: + assert parent is not None + try: + self._empty_listeners = self._empty_listener_reg[instance_cls] + except KeyError: + self._empty_listeners = self._empty_listener_reg[ + instance_cls + ] = { + ls.name: _EmptyListener(ls, instance_cls) + for ls in parent._event_descriptors + } + else: + self._empty_listeners = {} + + def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]: + # Assign EmptyListeners as attributes on demand + # to reduce startup time for new dispatch objects. + try: + ls = self._empty_listeners[name] + except KeyError: + raise AttributeError(name) + else: + setattr(self, ls.name, ls) + return ls + + @property + def _event_descriptors(self) -> Iterator[_ClsLevelDispatch[_ET]]: + for k in self._event_names: + # Yield _ClsLevelDispatch related + # to relevant event name. + yield getattr(self, k) + + def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None: + return self._events._listen(event_key, **kw) + + def _for_class(self, instance_cls: Type[_ET]) -> _Dispatch[_ET]: + return self.__class__(self, instance_cls) + + def _for_instance(self, instance: _ET) -> _Dispatch[_ET]: + instance_cls = instance.__class__ + return self._for_class(instance_cls) + + def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]: + """Create a 'join' of this :class:`._Dispatch` and another. + + This new dispatcher will dispatch events to both + :class:`._Dispatch` objects. + + """ + assert "_joined_dispatch_cls" in self.__class__.__dict__ + + return self._joined_dispatch_cls(self, other) + + def __reduce__(self) -> Union[str, Tuple[Any, ...]]: + return _UnpickleDispatch(), (self._instance_cls,) + + def _update( + self, other: _Dispatch[_ET], only_propagate: bool = True + ) -> None: + """Populate from the listeners in another :class:`_Dispatch` + object.""" + for ls in other._event_descriptors: + if isinstance(ls, _EmptyListener): + continue + getattr(self, ls.name).for_modify(self)._update( + ls, only_propagate=only_propagate + ) + + def _clear(self) -> None: + for ls in self._event_descriptors: + ls.for_modify(self).clear() + + +def _remove_dispatcher(cls: Type[_HasEventsDispatch[_ET]]) -> None: + for k in cls.dispatch._event_names: + _registrars[k].remove(cls) + if not _registrars[k]: + del _registrars[k] + + +class _HasEventsDispatch(Generic[_ET]): + _dispatch_target: Optional[Type[_ET]] + """class which will receive the .dispatch collection""" + + dispatch: _Dispatch[_ET] + """reference back to the _Dispatch class. + + Bidirectional against _Dispatch._events + + """ + + if typing.TYPE_CHECKING: + + def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]: ... + + def __init_subclass__(cls) -> None: + """Intercept new Event subclasses and create associated _Dispatch + classes.""" + + cls._create_dispatcher_class(cls.__name__, cls.__bases__, cls.__dict__) + + @classmethod + def _accept_with( + cls, target: Union[_ET, Type[_ET]], identifier: str + ) -> Optional[Union[_ET, Type[_ET]]]: + raise NotImplementedError() + + @classmethod + def _listen( + cls, + event_key: _EventKey[_ET], + *, + propagate: bool = False, + insert: bool = False, + named: bool = False, + asyncio: bool = False, + ) -> None: + raise NotImplementedError() + + @staticmethod + def _set_dispatch( + klass: Type[_HasEventsDispatch[_ET]], + dispatch_cls: Type[_Dispatch[_ET]], + ) -> _Dispatch[_ET]: + # This allows an Events subclass to define additional utility + # methods made available to the target via + # "self.dispatch._events." + # @staticmethod to allow easy "super" calls while in a metaclass + # constructor. + klass.dispatch = dispatch_cls(None) + dispatch_cls._events = klass + return klass.dispatch + + @classmethod + def _create_dispatcher_class( + cls, classname: str, bases: Tuple[type, ...], dict_: Mapping[str, Any] + ) -> None: + """Create a :class:`._Dispatch` class corresponding to an + :class:`.Events` class.""" + + # there's all kinds of ways to do this, + # i.e. make a Dispatch class that shares the '_listen' method + # of the Event class, this is the straight monkeypatch. + if hasattr(cls, "dispatch"): + dispatch_base = cls.dispatch.__class__ + else: + dispatch_base = _Dispatch + + event_names = [k for k in dict_ if _is_event_name(k)] + dispatch_cls = cast( + "Type[_Dispatch[_ET]]", + type( + "%sDispatch" % classname, + (dispatch_base,), + {"__slots__": event_names}, + ), + ) + + dispatch_cls._event_names = event_names + dispatch_inst = cls._set_dispatch(cls, dispatch_cls) + for k in dispatch_cls._event_names: + setattr(dispatch_inst, k, _ClsLevelDispatch(cls, dict_[k])) + _registrars[k].append(cls) + + for super_ in dispatch_cls.__bases__: + if issubclass(super_, _Dispatch) and super_ is not _Dispatch: + for ls in super_._events.dispatch._event_descriptors: + setattr(dispatch_inst, ls.name, ls) + dispatch_cls._event_names.append(ls.name) + + if getattr(cls, "_dispatch_target", None): + dispatch_target_cls = cls._dispatch_target + assert dispatch_target_cls is not None + if ( + hasattr(dispatch_target_cls, "__slots__") + and "_slots_dispatch" in dispatch_target_cls.__slots__ + ): + dispatch_target_cls.dispatch = slots_dispatcher(cls) + else: + dispatch_target_cls.dispatch = dispatcher(cls) + + klass = type( + "Joined%s" % dispatch_cls.__name__, + (_JoinedDispatcher,), + {"__slots__": event_names}, + ) + dispatch_cls._joined_dispatch_cls = klass + + # establish pickle capability by adding it to this module + globals()[klass.__name__] = klass + + +class _JoinedDispatcher(_DispatchCommon[_ET]): + """Represent a connection between two _Dispatch objects.""" + + __slots__ = "local", "parent", "_instance_cls" + + local: _DispatchCommon[_ET] + parent: _DispatchCommon[_ET] + _instance_cls: Optional[Type[_ET]] + + def __init__( + self, local: _DispatchCommon[_ET], parent: _DispatchCommon[_ET] + ): + self.local = local + self.parent = parent + self._instance_cls = self.local._instance_cls + + def __reduce__(self) -> Any: + return (self.__class__, (self.local, self.parent)) + + def __getattr__(self, name: str) -> _JoinedListener[_ET]: + # Assign _JoinedListeners as attributes on demand + # to reduce startup time for new dispatch objects. + ls = getattr(self.local, name) + jl = _JoinedListener(self.parent, ls.name, ls) + setattr(self, ls.name, jl) + return jl + + def _listen(self, event_key: _EventKey[_ET], **kw: Any) -> None: + return self.parent._listen(event_key, **kw) + + @property + def _events(self) -> Type[_HasEventsDispatch[_ET]]: + return self.parent._events + + +class Events(_HasEventsDispatch[_ET]): + """Define event listening functions for a particular target type.""" + + @classmethod + def _accept_with( + cls, target: Union[_ET, Type[_ET]], identifier: str + ) -> Optional[Union[_ET, Type[_ET]]]: + def dispatch_is(*types: Type[Any]) -> bool: + return all(isinstance(target.dispatch, t) for t in types) + + def dispatch_parent_is(t: Type[Any]) -> bool: + parent = cast("_JoinedDispatcher[_ET]", target.dispatch).parent + while isinstance(parent, _JoinedDispatcher): + parent = cast("_JoinedDispatcher[_ET]", parent).parent + + return isinstance(parent, t) + + # Mapper, ClassManager, Session override this to + # also accept classes, scoped_sessions, sessionmakers, etc. + if hasattr(target, "dispatch"): + if ( + dispatch_is(cls.dispatch.__class__) + or dispatch_is(type, cls.dispatch.__class__) + or ( + dispatch_is(_JoinedDispatcher) + and dispatch_parent_is(cls.dispatch.__class__) + ) + ): + return target + + return None + + @classmethod + def _listen( + cls, + event_key: _EventKey[_ET], + *, + propagate: bool = False, + insert: bool = False, + named: bool = False, + asyncio: bool = False, + ) -> None: + event_key.base_listen( + propagate=propagate, insert=insert, named=named, asyncio=asyncio + ) + + @classmethod + def _remove(cls, event_key: _EventKey[_ET]) -> None: + event_key.remove() + + @classmethod + def _clear(cls) -> None: + cls.dispatch._clear() + + +class dispatcher(Generic[_ET]): + """Descriptor used by target classes to + deliver the _Dispatch class at the class level + and produce new _Dispatch instances for target + instances. + + """ + + def __init__(self, events: Type[_HasEventsDispatch[_ET]]): + self.dispatch = events.dispatch + self.events = events + + @overload + def __get__( + self, obj: Literal[None], cls: Type[Any] + ) -> Type[_Dispatch[_ET]]: ... + + @overload + def __get__(self, obj: Any, cls: Type[Any]) -> _DispatchCommon[_ET]: ... + + def __get__(self, obj: Any, cls: Type[Any]) -> Any: + if obj is None: + return self.dispatch + + disp = self.dispatch._for_instance(obj) + try: + obj.__dict__["dispatch"] = disp + except AttributeError as ae: + raise TypeError( + "target %r doesn't have __dict__, should it be " + "defining _slots_dispatch?" % (obj,) + ) from ae + return disp + + +class slots_dispatcher(dispatcher[_ET]): + def __get__(self, obj: Any, cls: Type[Any]) -> Any: + if obj is None: + return self.dispatch + + if hasattr(obj, "_slots_dispatch"): + return obj._slots_dispatch + + disp = self.dispatch._for_instance(obj) + obj._slots_dispatch = disp + return disp diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/legacy.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..3d369e70586894438f5fc2f79b0a6777fa00bbba --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/legacy.py @@ -0,0 +1,258 @@ +# event/legacy.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Routines to handle adaption of legacy call signatures, +generation of deprecation notes and docstrings. + +""" +from __future__ import annotations + +import typing +from typing import Any +from typing import Callable +from typing import List +from typing import Optional +from typing import Tuple +from typing import Type +from typing import TypeVar + +from .registry import _ET +from .registry import _ListenerFnType +from .. import util +from ..util.compat import FullArgSpec + +if typing.TYPE_CHECKING: + from .attr import _ClsLevelDispatch + from .base import _HasEventsDispatch + + +_F = TypeVar("_F", bound=Callable[..., Any]) + +_LegacySignatureType = Tuple[str, List[str], Callable[..., Any]] + + +def _legacy_signature( + since: str, + argnames: List[str], + converter: Optional[Callable[..., Any]] = None, +) -> Callable[[_F], _F]: + """legacy sig decorator + + + :param since: string version for deprecation warning + :param argnames: list of strings, which is *all* arguments that the legacy + version accepted, including arguments that are still there + :param converter: lambda that will accept tuple of this full arg signature + and return tuple of new arg signature. + + """ + + def leg(fn: _F) -> _F: + if not hasattr(fn, "_legacy_signatures"): + fn._legacy_signatures = [] # type: ignore[attr-defined] + fn._legacy_signatures.append((since, argnames, converter)) # type: ignore[attr-defined] # noqa: E501 + return fn + + return leg + + +def _omit_standard_example(fn: _F) -> _F: + fn._omit_standard_example = True # type: ignore[attr-defined] + return fn + + +def _wrap_fn_for_legacy( + dispatch_collection: _ClsLevelDispatch[_ET], + fn: _ListenerFnType, + argspec: FullArgSpec, +) -> _ListenerFnType: + for since, argnames, conv in dispatch_collection.legacy_signatures: + if argnames[-1] == "**kw": + has_kw = True + argnames = argnames[0:-1] + else: + has_kw = False + + if len(argnames) == len(argspec.args) and has_kw is bool( + argspec.varkw + ): + formatted_def = "def %s(%s%s)" % ( + dispatch_collection.name, + ", ".join(dispatch_collection.arg_names), + ", **kw" if has_kw else "", + ) + warning_txt = ( + 'The argument signature for the "%s.%s" event listener ' + "has changed as of version %s, and conversion for " + "the old argument signature will be removed in a " + 'future release. The new signature is "%s"' + % ( + dispatch_collection.clsname, + dispatch_collection.name, + since, + formatted_def, + ) + ) + + if conv is not None: + assert not has_kw + + def wrap_leg(*args: Any, **kw: Any) -> Any: + util.warn_deprecated(warning_txt, version=since) + assert conv is not None + return fn(*conv(*args)) + + else: + + def wrap_leg(*args: Any, **kw: Any) -> Any: + util.warn_deprecated(warning_txt, version=since) + argdict = dict(zip(dispatch_collection.arg_names, args)) + args_from_dict = [argdict[name] for name in argnames] + if has_kw: + return fn(*args_from_dict, **kw) + else: + return fn(*args_from_dict) + + return wrap_leg + else: + return fn + + +def _indent(text: str, indent: str) -> str: + return "\n".join(indent + line for line in text.split("\n")) + + +def _standard_listen_example( + dispatch_collection: _ClsLevelDispatch[_ET], + sample_target: Any, + fn: _ListenerFnType, +) -> str: + example_kw_arg = _indent( + "\n".join( + "%(arg)s = kw['%(arg)s']" % {"arg": arg} + for arg in dispatch_collection.arg_names[0:2] + ), + " ", + ) + if dispatch_collection.legacy_signatures: + current_since = max( + since + for since, args, conv in dispatch_collection.legacy_signatures + ) + else: + current_since = None + text = ( + "from sqlalchemy import event\n\n\n" + "@event.listens_for(%(sample_target)s, '%(event_name)s')\n" + "def receive_%(event_name)s(" + "%(named_event_arguments)s%(has_kw_arguments)s):\n" + " \"listen for the '%(event_name)s' event\"\n" + "\n # ... (event handling logic) ...\n" + ) + + text %= { + "current_since": ( + " (arguments as of %s)" % current_since if current_since else "" + ), + "event_name": fn.__name__, + "has_kw_arguments": ", **kw" if dispatch_collection.has_kw else "", + "named_event_arguments": ", ".join(dispatch_collection.arg_names), + "example_kw_arg": example_kw_arg, + "sample_target": sample_target, + } + return text + + +def _legacy_listen_examples( + dispatch_collection: _ClsLevelDispatch[_ET], + sample_target: str, + fn: _ListenerFnType, +) -> str: + text = "" + for since, args, conv in dispatch_collection.legacy_signatures: + text += ( + "\n# DEPRECATED calling style (pre-%(since)s, " + "will be removed in a future release)\n" + "@event.listens_for(%(sample_target)s, '%(event_name)s')\n" + "def receive_%(event_name)s(" + "%(named_event_arguments)s%(has_kw_arguments)s):\n" + " \"listen for the '%(event_name)s' event\"\n" + "\n # ... (event handling logic) ...\n" + % { + "since": since, + "event_name": fn.__name__, + "has_kw_arguments": ( + " **kw" if dispatch_collection.has_kw else "" + ), + "named_event_arguments": ", ".join(args), + "sample_target": sample_target, + } + ) + return text + + +def _version_signature_changes( + parent_dispatch_cls: Type[_HasEventsDispatch[_ET]], + dispatch_collection: _ClsLevelDispatch[_ET], +) -> str: + since, args, conv = dispatch_collection.legacy_signatures[0] + return ( + "\n.. versionchanged:: %(since)s\n" + " The :meth:`.%(clsname)s.%(event_name)s` event now accepts the \n" + " arguments %(named_event_arguments)s%(has_kw_arguments)s.\n" + " Support for listener functions which accept the previous \n" + ' argument signature(s) listed above as "deprecated" will be \n' + " removed in a future release." + % { + "since": since, + "clsname": parent_dispatch_cls.__name__, + "event_name": dispatch_collection.name, + "named_event_arguments": ", ".join( + ":paramref:`.%(clsname)s.%(event_name)s.%(param_name)s`" + % { + "clsname": parent_dispatch_cls.__name__, + "event_name": dispatch_collection.name, + "param_name": param_name, + } + for param_name in dispatch_collection.arg_names + ), + "has_kw_arguments": ", **kw" if dispatch_collection.has_kw else "", + } + ) + + +def _augment_fn_docs( + dispatch_collection: _ClsLevelDispatch[_ET], + parent_dispatch_cls: Type[_HasEventsDispatch[_ET]], + fn: _ListenerFnType, +) -> str: + if getattr(fn, "_omit_standard_example", False): + assert fn.__doc__ + return fn.__doc__ + + header = ( + ".. container:: event_signatures\n\n" + " Example argument forms::\n" + "\n" + ) + + sample_target = getattr(parent_dispatch_cls, "_target_class_doc", "obj") + text = header + _indent( + _standard_listen_example(dispatch_collection, sample_target, fn), + " " * 8, + ) + if dispatch_collection.legacy_signatures: + text += _indent( + _legacy_listen_examples(dispatch_collection, sample_target, fn), + " " * 8, + ) + + text += _version_signature_changes( + parent_dispatch_cls, dispatch_collection + ) + + return util.inject_docstring_text(fn.__doc__, text, 1) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/event/registry.py b/python/user_packages/Python313/site-packages/sqlalchemy/event/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..251d7eb3fa1a88ae25122dfb3f512a636262cbac --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/event/registry.py @@ -0,0 +1,390 @@ +# event/registry.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Provides managed registration services on behalf of :func:`.listen` +arguments. + +By "managed registration", we mean that event listening functions and +other objects can be added to various collections in such a way that their +membership in all those collections can be revoked at once, based on +an equivalent :class:`._EventKey`. + +""" +from __future__ import annotations + +import collections +import types +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Deque +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import Optional +from typing import Tuple +from typing import TypeVar +from typing import Union +import weakref + +from .. import exc +from .. import util + +if typing.TYPE_CHECKING: + from .attr import RefCollection + from .base import dispatcher + +_ListenerFnType = Callable[..., Any] +_ListenerFnKeyType = Union[int, Tuple[int, int]] +_EventKeyTupleType = Tuple[int, str, _ListenerFnKeyType] + + +_ET = TypeVar("_ET", bound="EventTarget") + + +class EventTarget: + """represents an event target, that is, something we can listen on + either with that target as a class or as an instance. + + Examples include: Connection, Mapper, Table, Session, + InstrumentedAttribute, Engine, Pool, Dialect. + + """ + + __slots__ = () + + dispatch: dispatcher[Any] + + +_RefCollectionToListenerType = Dict[ + "weakref.ref[RefCollection[Any]]", + "weakref.ref[_ListenerFnType]", +] + +_key_to_collection: Dict[_EventKeyTupleType, _RefCollectionToListenerType] = ( + collections.defaultdict(dict) +) +""" +Given an original listen() argument, can locate all +listener collections and the listener fn contained + +(target, identifier, fn) -> { + ref(listenercollection) -> ref(listener_fn) + ref(listenercollection) -> ref(listener_fn) + ref(listenercollection) -> ref(listener_fn) + } +""" + +_ListenerToEventKeyType = Dict[ + "weakref.ref[_ListenerFnType]", + _EventKeyTupleType, +] +_collection_to_key: Dict[ + weakref.ref[RefCollection[Any]], + _ListenerToEventKeyType, +] = collections.defaultdict(dict) +""" +Given a _ListenerCollection or _ClsLevelListener, can locate +all the original listen() arguments and the listener fn contained + +ref(listenercollection) -> { + ref(listener_fn) -> (target, identifier, fn), + ref(listener_fn) -> (target, identifier, fn), + ref(listener_fn) -> (target, identifier, fn), + } +""" + + +def _collection_gced(ref: weakref.ref[Any]) -> None: + # defaultdict, so can't get a KeyError + if not _collection_to_key or ref not in _collection_to_key: + return + + ref = cast("weakref.ref[RefCollection[EventTarget]]", ref) + + listener_to_key = _collection_to_key.pop(ref) + for key in listener_to_key.values(): + if key in _key_to_collection: + # defaultdict, so can't get a KeyError + dispatch_reg = _key_to_collection[key] + dispatch_reg.pop(ref) + if not dispatch_reg: + _key_to_collection.pop(key) + + +def _stored_in_collection( + event_key: _EventKey[_ET], owner: RefCollection[_ET] +) -> bool: + key = event_key._key + + dispatch_reg = _key_to_collection[key] + + owner_ref = owner.ref + listen_ref = weakref.ref(event_key._listen_fn) + + if owner_ref in dispatch_reg: + return False + + dispatch_reg[owner_ref] = listen_ref + + listener_to_key = _collection_to_key[owner_ref] + listener_to_key[listen_ref] = key + + return True + + +def _removed_from_collection( + event_key: _EventKey[_ET], owner: RefCollection[_ET] +) -> None: + key = event_key._key + + dispatch_reg = _key_to_collection[key] + + listen_ref = weakref.ref(event_key._listen_fn) + + owner_ref = owner.ref + dispatch_reg.pop(owner_ref, None) + if not dispatch_reg: + del _key_to_collection[key] + + if owner_ref in _collection_to_key: + listener_to_key = _collection_to_key[owner_ref] + # see #12216 - this guards against a removal that already occurred + # here. however, I cannot come up with a test that shows any negative + # side effects occurring from this removal happening, even though an + # event key may still be referenced from a clsleveldispatch here + listener_to_key.pop(listen_ref, None) + + +def _stored_in_collection_multi( + newowner: RefCollection[_ET], + oldowner: RefCollection[_ET], + elements: Iterable[_ListenerFnType], +) -> None: + if not elements: + return + + oldowner_ref = oldowner.ref + newowner_ref = newowner.ref + + old_listener_to_key = _collection_to_key[oldowner_ref] + new_listener_to_key = _collection_to_key[newowner_ref] + + for listen_fn in elements: + listen_ref = weakref.ref(listen_fn) + try: + key = old_listener_to_key[listen_ref] + except KeyError: + # can occur during interpreter shutdown. + # see #6740 + continue + + try: + dispatch_reg = _key_to_collection[key] + except KeyError: + continue + + if newowner_ref in dispatch_reg: + assert dispatch_reg[newowner_ref] == listen_ref + else: + dispatch_reg[newowner_ref] = listen_ref + + new_listener_to_key[listen_ref] = key + + +def _clear( + owner: RefCollection[_ET], + elements: Iterable[_ListenerFnType], +) -> None: + if not elements: + return + + owner_ref = owner.ref + listener_to_key = _collection_to_key[owner_ref] + for listen_fn in elements: + listen_ref = weakref.ref(listen_fn) + key = listener_to_key[listen_ref] + dispatch_reg = _key_to_collection[key] + dispatch_reg.pop(owner_ref, None) + + if not dispatch_reg: + del _key_to_collection[key] + + +class _EventKey(Generic[_ET]): + """Represent :func:`.listen` arguments.""" + + __slots__ = ( + "target", + "identifier", + "fn", + "fn_key", + "fn_wrap", + "dispatch_target", + ) + + target: _ET + identifier: str + fn: _ListenerFnType + fn_key: _ListenerFnKeyType + dispatch_target: Any + _fn_wrap: Optional[_ListenerFnType] + + def __init__( + self, + target: _ET, + identifier: str, + fn: _ListenerFnType, + dispatch_target: Any, + _fn_wrap: Optional[_ListenerFnType] = None, + ): + self.target = target + self.identifier = identifier + self.fn = fn + if isinstance(fn, types.MethodType): + self.fn_key = id(fn.__func__), id(fn.__self__) + else: + self.fn_key = id(fn) + self.fn_wrap = _fn_wrap + self.dispatch_target = dispatch_target + + @property + def _key(self) -> _EventKeyTupleType: + return (id(self.target), self.identifier, self.fn_key) + + def with_wrapper(self, fn_wrap: _ListenerFnType) -> _EventKey[_ET]: + if fn_wrap is self._listen_fn: + return self + else: + return _EventKey( + self.target, + self.identifier, + self.fn, + self.dispatch_target, + _fn_wrap=fn_wrap, + ) + + def with_dispatch_target(self, dispatch_target: Any) -> _EventKey[_ET]: + if dispatch_target is self.dispatch_target: + return self + else: + return _EventKey( + self.target, + self.identifier, + self.fn, + dispatch_target, + _fn_wrap=self.fn_wrap, + ) + + def listen(self, *args: Any, **kw: Any) -> None: + once = kw.pop("once", False) + once_unless_exception = kw.pop("_once_unless_exception", False) + named = kw.pop("named", False) + + target, identifier, fn = ( + self.dispatch_target, + self.identifier, + self._listen_fn, + ) + + dispatch_collection = getattr(target.dispatch, identifier) + + adjusted_fn = dispatch_collection._adjust_fn_spec(fn, named) + + self = self.with_wrapper(adjusted_fn) + + stub_function = getattr( + self.dispatch_target.dispatch._events, self.identifier + ) + if hasattr(stub_function, "_sa_warn"): + stub_function._sa_warn() + + if once or once_unless_exception: + self.with_wrapper( + util.only_once( + self._listen_fn, retry_on_exception=once_unless_exception + ) + ).listen(*args, **kw) + else: + self.dispatch_target.dispatch._listen(self, *args, **kw) + + def remove(self) -> None: + key = self._key + + if key not in _key_to_collection: + raise exc.InvalidRequestError( + "No listeners found for event %s / %r / %s " + % (self.target, self.identifier, self.fn) + ) + + dispatch_reg = _key_to_collection.pop(key) + + for collection_ref, listener_ref in dispatch_reg.items(): + collection = collection_ref() + listener_fn = listener_ref() + if collection is not None and listener_fn is not None: + collection.remove(self.with_wrapper(listener_fn)) + + def contains(self) -> bool: + """Return True if this event key is registered to listen.""" + return self._key in _key_to_collection + + def base_listen( + self, + propagate: bool = False, + insert: bool = False, + named: bool = False, + retval: Optional[bool] = None, + asyncio: bool = False, + ) -> None: + target, identifier = self.dispatch_target, self.identifier + + dispatch_collection = getattr(target.dispatch, identifier) + + for_modify = dispatch_collection.for_modify(target.dispatch) + if asyncio: + for_modify._set_asyncio() + + if insert: + for_modify.insert(self, propagate) + else: + for_modify.append(self, propagate) + + @property + def _listen_fn(self) -> _ListenerFnType: + return self.fn_wrap or self.fn + + def append_to_list( + self, + owner: RefCollection[_ET], + list_: Deque[_ListenerFnType], + ) -> bool: + if _stored_in_collection(self, owner): + list_.append(self._listen_fn) + return True + else: + return False + + def remove_from_list( + self, + owner: RefCollection[_ET], + list_: Deque[_ListenerFnType], + ) -> None: + _removed_from_collection(self, owner) + list_.remove(self._listen_fn) + + def prepend_to_list( + self, + owner: RefCollection[_ET], + list_: Deque[_ListenerFnType], + ) -> bool: + if _stored_in_collection(self, owner): + list_.appendleft(self._listen_fn) + return True + else: + return False diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..523789f4e486ee93573001caa81b244bfe76aa8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/__init__.py @@ -0,0 +1,11 @@ +# ext/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from .. import util as _sa_util + + +_sa_util.preloaded.import_prefix("sqlalchemy.ext") diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/associationproxy.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/associationproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..0add5e4861d85ef2834744f56b0f4dce8ea9910a --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/associationproxy.py @@ -0,0 +1,2027 @@ +# ext/associationproxy.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Contain the ``AssociationProxy`` class. + +The ``AssociationProxy`` is a Python property object which provides +transparent proxied access to the endpoint of an association object. + +See the example ``examples/association/proxied_association.py``. + +""" +from __future__ import annotations + +import operator +import typing +from typing import AbstractSet +from typing import Any +from typing import Callable +from typing import cast +from typing import Collection +from typing import Dict +from typing import Generic +from typing import ItemsView +from typing import Iterable +from typing import Iterator +from typing import KeysView +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import MutableSequence +from typing import MutableSet +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Set +from typing import Tuple +from typing import Type +from typing import TypeVar +from typing import Union +from typing import ValuesView + +from .. import ColumnElement +from .. import exc +from .. import inspect +from .. import orm +from .. import util +from ..orm import collections +from ..orm import InspectionAttrExtensionType +from ..orm import interfaces +from ..orm import ORMDescriptor +from ..orm.base import SQLORMOperations +from ..orm.interfaces import _AttributeOptions +from ..orm.interfaces import _DCAttributeOptions +from ..orm.interfaces import _DEFAULT_ATTRIBUTE_OPTIONS +from ..sql import operators +from ..sql import or_ +from ..sql.base import _NoArg +from ..util.typing import Literal +from ..util.typing import Protocol +from ..util.typing import Self +from ..util.typing import SupportsIndex +from ..util.typing import SupportsKeysAndGetItem + +if typing.TYPE_CHECKING: + from ..orm.interfaces import MapperProperty + from ..orm.interfaces import PropComparator + from ..orm.mapper import Mapper + from ..sql._typing import _ColumnExpressionArgument + from ..sql._typing import _InfoType + + +_T = TypeVar("_T", bound=Any) +_T_co = TypeVar("_T_co", bound=Any, covariant=True) +_T_con = TypeVar("_T_con", bound=Any, contravariant=True) +_S = TypeVar("_S", bound=Any) +_KT = TypeVar("_KT", bound=Any) +_VT = TypeVar("_VT", bound=Any) + + +def association_proxy( + target_collection: str, + attr: str, + *, + creator: Optional[_CreatorProtocol] = None, + getset_factory: Optional[_GetSetFactoryProtocol] = None, + proxy_factory: Optional[_ProxyFactoryProtocol] = None, + proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None, + info: Optional[_InfoType] = None, + cascade_scalar_deletes: bool = False, + create_on_none_assignment: bool = False, + init: Union[_NoArg, bool] = _NoArg.NO_ARG, + repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 + default: Optional[Any] = _NoArg.NO_ARG, + default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, + compare: Union[_NoArg, bool] = _NoArg.NO_ARG, + kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, + hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 + dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] = _NoArg.NO_ARG, +) -> AssociationProxy[Any]: + r"""Return a Python property implementing a view of a target + attribute which references an attribute on members of the + target. + + The returned value is an instance of :class:`.AssociationProxy`. + + Implements a Python property representing a relationship as a collection + of simpler values, or a scalar value. The proxied property will mimic + the collection type of the target (list, dict or set), or, in the case of + a one to one relationship, a simple scalar value. + + :param target_collection: Name of the attribute that is the immediate + target. This attribute is typically mapped by + :func:`~sqlalchemy.orm.relationship` to link to a target collection, but + can also be a many-to-one or non-scalar relationship. + + :param attr: Attribute on the associated instance or instances that + are available on instances of the target object. + + :param creator: optional. + + Defines custom behavior when new items are added to the proxied + collection. + + By default, adding new items to the collection will trigger a + construction of an instance of the target object, passing the given + item as a positional argument to the target constructor. For cases + where this isn't sufficient, :paramref:`.association_proxy.creator` + can supply a callable that will construct the object in the + appropriate way, given the item that was passed. + + For list- and set- oriented collections, a single argument is + passed to the callable. For dictionary oriented collections, two + arguments are passed, corresponding to the key and value. + + The :paramref:`.association_proxy.creator` callable is also invoked + for scalar (i.e. many-to-one, one-to-one) relationships. If the + current value of the target relationship attribute is ``None``, the + callable is used to construct a new object. If an object value already + exists, the given attribute value is populated onto that object. + + .. seealso:: + + :ref:`associationproxy_creator` + + :param cascade_scalar_deletes: when True, indicates that setting + the proxied value to ``None``, or deleting it via ``del``, should + also remove the source object. Only applies to scalar attributes. + Normally, removing the proxied target will not remove the proxy + source, as this object may have other state that is still to be + kept. + + .. versionadded:: 1.3 + + .. seealso:: + + :ref:`cascade_scalar_deletes` - complete usage example + + :param create_on_none_assignment: when True, indicates that setting + the proxied value to ``None`` should **create** the source object + if it does not exist, using the creator. Only applies to scalar + attributes. This is mutually exclusive + vs. the :paramref:`.association_proxy.cascade_scalar_deletes`. + + .. versionadded:: 2.0.18 + + :param init: Specific to :ref:`orm_declarative_native_dataclasses`, + specifies if the mapped attribute should be part of the ``__init__()`` + method as generated by the dataclass process. + + .. versionadded:: 2.0.0b4 + + :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, + specifies if the attribute established by this :class:`.AssociationProxy` + should be part of the ``__repr__()`` method as generated by the dataclass + process. + + .. versionadded:: 2.0.0b4 + + :param default_factory: Specific to + :ref:`orm_declarative_native_dataclasses`, specifies a default-value + generation function that will take place as part of the ``__init__()`` + method as generated by the dataclass process. + + .. versionadded:: 2.0.0b4 + + :param compare: Specific to + :ref:`orm_declarative_native_dataclasses`, indicates if this field + should be included in comparison operations when generating the + ``__eq__()`` and ``__ne__()`` methods for the mapped class. + + .. versionadded:: 2.0.0b4 + + :param kw_only: Specific to :ref:`orm_declarative_native_dataclasses`, + indicates if this field should be marked as keyword-only when generating + the ``__init__()`` method as generated by the dataclass process. + + .. versionadded:: 2.0.0b4 + + :param hash: Specific to + :ref:`orm_declarative_native_dataclasses`, controls if this field + is included when generating the ``__hash__()`` method for the mapped + class. + + .. versionadded:: 2.0.36 + + :param dataclass_metadata: Specific to + :ref:`orm_declarative_native_dataclasses`, supplies metadata + to be attached to the generated dataclass field. + + .. versionadded:: 2.0.42 + + :param info: optional, will be assigned to + :attr:`.AssociationProxy.info` if present. + + + The following additional parameters involve injection of custom behaviors + within the :class:`.AssociationProxy` object and are for advanced use + only: + + :param getset_factory: Optional. Proxied attribute access is + automatically handled by routines that get and set values based on + the `attr` argument for this proxy. + + If you would like to customize this behavior, you may supply a + `getset_factory` callable that produces a tuple of `getter` and + `setter` functions. The factory is called with two arguments, the + abstract type of the underlying collection and this proxy instance. + + :param proxy_factory: Optional. The type of collection to emulate is + determined by sniffing the target collection. If your collection + type can't be determined by duck typing or you'd like to use a + different collection implementation, you may supply a factory + function to produce those collections. Only applicable to + non-scalar relationships. + + :param proxy_bulk_set: Optional, use with proxy_factory. + + + """ + return AssociationProxy( + target_collection, + attr, + creator=creator, + getset_factory=getset_factory, + proxy_factory=proxy_factory, + proxy_bulk_set=proxy_bulk_set, + info=info, + cascade_scalar_deletes=cascade_scalar_deletes, + create_on_none_assignment=create_on_none_assignment, + attribute_options=_AttributeOptions( + init, + repr, + default, + default_factory, + compare, + kw_only, + hash, + dataclass_metadata, + ), + ) + + +class AssociationProxyExtensionType(InspectionAttrExtensionType): + ASSOCIATION_PROXY = "ASSOCIATION_PROXY" + """Symbol indicating an :class:`.InspectionAttr` that's + of type :class:`.AssociationProxy`. + + Is assigned to the :attr:`.InspectionAttr.extension_type` + attribute. + + """ + + +class _GetterProtocol(Protocol[_T_co]): + def __call__(self, instance: Any) -> _T_co: ... + + +# mypy 0.990 we are no longer allowed to make this Protocol[_T_con] +class _SetterProtocol(Protocol): ... + + +class _PlainSetterProtocol(_SetterProtocol, Protocol[_T_con]): + def __call__(self, instance: Any, value: _T_con) -> None: ... + + +class _DictSetterProtocol(_SetterProtocol, Protocol[_T_con]): + def __call__(self, instance: Any, key: Any, value: _T_con) -> None: ... + + +# mypy 0.990 we are no longer allowed to make this Protocol[_T_con] +class _CreatorProtocol(Protocol): ... + + +class _PlainCreatorProtocol(_CreatorProtocol, Protocol[_T_con]): + def __call__(self, value: _T_con) -> Any: ... + + +class _KeyCreatorProtocol(_CreatorProtocol, Protocol[_T_con]): + def __call__(self, key: Any, value: Optional[_T_con]) -> Any: ... + + +class _LazyCollectionProtocol(Protocol[_T]): + def __call__( + self, + ) -> Union[ + MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T] + ]: ... + + +class _GetSetFactoryProtocol(Protocol): + def __call__( + self, + collection_class: Optional[Type[Any]], + assoc_instance: AssociationProxyInstance[Any], + ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: ... + + +class _ProxyFactoryProtocol(Protocol): + def __call__( + self, + lazy_collection: _LazyCollectionProtocol[Any], + creator: _CreatorProtocol, + value_attr: str, + parent: AssociationProxyInstance[Any], + ) -> Any: ... + + +class _ProxyBulkSetProtocol(Protocol): + def __call__( + self, proxy: _AssociationCollection[Any], collection: Iterable[Any] + ) -> None: ... + + +class _AssociationProxyProtocol(Protocol[_T]): + """describes the interface of :class:`.AssociationProxy` + without including descriptor methods in the interface.""" + + creator: Optional[_CreatorProtocol] + key: str + target_collection: str + value_attr: str + cascade_scalar_deletes: bool + create_on_none_assignment: bool + getset_factory: Optional[_GetSetFactoryProtocol] + proxy_factory: Optional[_ProxyFactoryProtocol] + proxy_bulk_set: Optional[_ProxyBulkSetProtocol] + + @util.ro_memoized_property + def info(self) -> _InfoType: ... + + def for_class( + self, class_: Type[Any], obj: Optional[object] = None + ) -> AssociationProxyInstance[_T]: ... + + def _default_getset( + self, collection_class: Any + ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: ... + + +class AssociationProxy( + interfaces.InspectionAttrInfo, + ORMDescriptor[_T], + _DCAttributeOptions, + _AssociationProxyProtocol[_T], +): + """A descriptor that presents a read/write view of an object attribute.""" + + is_attribute = True + extension_type = AssociationProxyExtensionType.ASSOCIATION_PROXY + + def __init__( + self, + target_collection: str, + attr: str, + *, + creator: Optional[_CreatorProtocol] = None, + getset_factory: Optional[_GetSetFactoryProtocol] = None, + proxy_factory: Optional[_ProxyFactoryProtocol] = None, + proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None, + info: Optional[_InfoType] = None, + cascade_scalar_deletes: bool = False, + create_on_none_assignment: bool = False, + attribute_options: Optional[_AttributeOptions] = None, + ): + """Construct a new :class:`.AssociationProxy`. + + The :class:`.AssociationProxy` object is typically constructed using + the :func:`.association_proxy` constructor function. See the + description of :func:`.association_proxy` for a description of all + parameters. + + + """ + self.target_collection = target_collection + self.value_attr = attr + self.creator = creator + self.getset_factory = getset_factory + self.proxy_factory = proxy_factory + self.proxy_bulk_set = proxy_bulk_set + + if cascade_scalar_deletes and create_on_none_assignment: + raise exc.ArgumentError( + "The cascade_scalar_deletes and create_on_none_assignment " + "parameters are mutually exclusive." + ) + self.cascade_scalar_deletes = cascade_scalar_deletes + self.create_on_none_assignment = create_on_none_assignment + + self.key = "_%s_%s_%s" % ( + type(self).__name__, + target_collection, + id(self), + ) + if info: + self.info = info # type: ignore + + if ( + attribute_options + and attribute_options != _DEFAULT_ATTRIBUTE_OPTIONS + ): + self._has_dataclass_arguments = True + self._attribute_options = attribute_options + else: + self._has_dataclass_arguments = False + self._attribute_options = _DEFAULT_ATTRIBUTE_OPTIONS + + @overload + def __get__( + self, instance: Literal[None], owner: Literal[None] + ) -> Self: ... + + @overload + def __get__( + self, instance: Literal[None], owner: Any + ) -> AssociationProxyInstance[_T]: ... + + @overload + def __get__(self, instance: object, owner: Any) -> _T: ... + + def __get__( + self, instance: object, owner: Any + ) -> Union[AssociationProxyInstance[_T], _T, AssociationProxy[_T]]: + if owner is None: + return self + inst = self._as_instance(owner, instance) + if inst: + return inst.get(instance) + + assert instance is None + + return self + + def __set__(self, instance: object, values: _T) -> None: + class_ = type(instance) + self._as_instance(class_, instance).set(instance, values) + + def __delete__(self, instance: object) -> None: + class_ = type(instance) + self._as_instance(class_, instance).delete(instance) + + def for_class( + self, class_: Type[Any], obj: Optional[object] = None + ) -> AssociationProxyInstance[_T]: + r"""Return the internal state local to a specific mapped class. + + E.g., given a class ``User``:: + + class User(Base): + # ... + + keywords = association_proxy("kws", "keyword") + + If we access this :class:`.AssociationProxy` from + :attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the + target class for this proxy as mapped by ``User``:: + + inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class + + This returns an instance of :class:`.AssociationProxyInstance` that + is specific to the ``User`` class. The :class:`.AssociationProxy` + object remains agnostic of its parent class. + + :param class\_: the class that we are returning state for. + + :param obj: optional, an instance of the class that is required + if the attribute refers to a polymorphic target, e.g. where we have + to look at the type of the actual destination object to get the + complete path. + + .. versionadded:: 1.3 - :class:`.AssociationProxy` no longer stores + any state specific to a particular parent class; the state is now + stored in per-class :class:`.AssociationProxyInstance` objects. + + + """ + return self._as_instance(class_, obj) + + def _as_instance( + self, class_: Any, obj: Any + ) -> AssociationProxyInstance[_T]: + try: + inst = class_.__dict__[self.key + "_inst"] + except KeyError: + inst = None + + # avoid exception context + if inst is None: + owner = self._calc_owner(class_) + if owner is not None: + inst = AssociationProxyInstance.for_proxy(self, owner, obj) + setattr(class_, self.key + "_inst", inst) + else: + inst = None + + if inst is not None and not inst._is_canonical: + # the AssociationProxyInstance can't be generalized + # since the proxied attribute is not on the targeted + # class, only on subclasses of it, which might be + # different. only return for the specific + # object's current value + return inst._non_canonical_get_for_object(obj) # type: ignore + else: + return inst # type: ignore # TODO + + def _calc_owner(self, target_cls: Any) -> Any: + # we might be getting invoked for a subclass + # that is not mapped yet, in some declarative situations. + # save until we are mapped + try: + insp = inspect(target_cls) + except exc.NoInspectionAvailable: + # can't find a mapper, don't set owner. if we are a not-yet-mapped + # subclass, we can also scan through __mro__ to find a mapped + # class, but instead just wait for us to be called again against a + # mapped class normally. + return None + else: + return insp.mapper.class_manager.class_ + + def _default_getset( + self, collection_class: Any + ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: + attr = self.value_attr + _getter = operator.attrgetter(attr) + + def getter(instance: Any) -> Optional[Any]: + return _getter(instance) if instance is not None else None + + if collection_class is dict: + + def dict_setter(instance: Any, k: Any, value: Any) -> None: + setattr(instance, attr, value) + + return getter, dict_setter + + else: + + def plain_setter(o: Any, v: Any) -> None: + setattr(o, attr, v) + + return getter, plain_setter + + def __repr__(self) -> str: + return "AssociationProxy(%r, %r)" % ( + self.target_collection, + self.value_attr, + ) + + +# the pep-673 Self type does not work in Mypy for a "hybrid" +# style method that returns type or Self, so for one specific case +# we still need to use the pre-pep-673 workaround. +_Self = TypeVar("_Self", bound="AssociationProxyInstance[Any]") + + +class AssociationProxyInstance(SQLORMOperations[_T]): + """A per-class object that serves class- and object-specific results. + + This is used by :class:`.AssociationProxy` when it is invoked + in terms of a specific class or instance of a class, i.e. when it is + used as a regular Python descriptor. + + When referring to the :class:`.AssociationProxy` as a normal Python + descriptor, the :class:`.AssociationProxyInstance` is the object that + actually serves the information. Under normal circumstances, its presence + is transparent:: + + >>> User.keywords.scalar + False + + In the special case that the :class:`.AssociationProxy` object is being + accessed directly, in order to get an explicit handle to the + :class:`.AssociationProxyInstance`, use the + :meth:`.AssociationProxy.for_class` method:: + + proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User) + + # view if proxy object is scalar or not + >>> proxy_state.scalar + False + + .. versionadded:: 1.3 + + """ # noqa + + collection_class: Optional[Type[Any]] + parent: _AssociationProxyProtocol[_T] + + def __init__( + self, + parent: _AssociationProxyProtocol[_T], + owning_class: Type[Any], + target_class: Type[Any], + value_attr: str, + ): + self.parent = parent + self.key = parent.key + self.owning_class = owning_class + self.target_collection = parent.target_collection + self.collection_class = None + self.target_class = target_class + self.value_attr = value_attr + + target_class: Type[Any] + """The intermediary class handled by this + :class:`.AssociationProxyInstance`. + + Intercepted append/set/assignment events will result + in the generation of new instances of this class. + + """ + + @classmethod + def for_proxy( + cls, + parent: AssociationProxy[_T], + owning_class: Type[Any], + parent_instance: Any, + ) -> AssociationProxyInstance[_T]: + target_collection = parent.target_collection + value_attr = parent.value_attr + prop = cast( + "orm.RelationshipProperty[_T]", + orm.class_mapper(owning_class).get_property(target_collection), + ) + + # this was never asserted before but this should be made clear. + if not isinstance(prop, orm.RelationshipProperty): + raise NotImplementedError( + "association proxy to a non-relationship " + "intermediary is not supported" + ) from None + + target_class = prop.mapper.class_ + + try: + target_assoc = cast( + "AssociationProxyInstance[_T]", + cls._cls_unwrap_target_assoc_proxy(target_class, value_attr), + ) + except AttributeError: + # the proxied attribute doesn't exist on the target class; + # return an "ambiguous" instance that will work on a per-object + # basis + return AmbiguousAssociationProxyInstance( + parent, owning_class, target_class, value_attr + ) + except Exception as err: + raise exc.InvalidRequestError( + f"Association proxy received an unexpected error when " + f"trying to retrieve attribute " + f'"{target_class.__name__}.{parent.value_attr}" from ' + f'class "{target_class.__name__}": {err}' + ) from err + else: + return cls._construct_for_assoc( + target_assoc, parent, owning_class, target_class, value_attr + ) + + @classmethod + def _construct_for_assoc( + cls, + target_assoc: Optional[AssociationProxyInstance[_T]], + parent: _AssociationProxyProtocol[_T], + owning_class: Type[Any], + target_class: Type[Any], + value_attr: str, + ) -> AssociationProxyInstance[_T]: + if target_assoc is not None: + return ObjectAssociationProxyInstance( + parent, owning_class, target_class, value_attr + ) + + attr = getattr(target_class, value_attr) + if not hasattr(attr, "_is_internal_proxy"): + return AmbiguousAssociationProxyInstance( + parent, owning_class, target_class, value_attr + ) + is_object = attr._impl_uses_objects + if is_object: + return ObjectAssociationProxyInstance( + parent, owning_class, target_class, value_attr + ) + else: + return ColumnAssociationProxyInstance( + parent, owning_class, target_class, value_attr + ) + + def _get_property(self) -> MapperProperty[Any]: + return orm.class_mapper(self.owning_class).get_property( + self.target_collection + ) + + @property + def _comparator(self) -> PropComparator[Any]: + return getattr( # type: ignore + self.owning_class, self.target_collection + ).comparator + + def __clause_element__(self) -> NoReturn: + raise NotImplementedError( + "The association proxy can't be used as a plain column " + "expression; it only works inside of a comparison expression" + ) + + @classmethod + def _cls_unwrap_target_assoc_proxy( + cls, target_class: Any, value_attr: str + ) -> Optional[AssociationProxyInstance[_T]]: + attr = getattr(target_class, value_attr) + assert not isinstance(attr, AssociationProxy) + if isinstance(attr, AssociationProxyInstance): + return attr + return None + + @util.memoized_property + def _unwrap_target_assoc_proxy( + self, + ) -> Optional[AssociationProxyInstance[_T]]: + return self._cls_unwrap_target_assoc_proxy( + self.target_class, self.value_attr + ) + + @property + def remote_attr(self) -> SQLORMOperations[_T]: + """The 'remote' class attribute referenced by this + :class:`.AssociationProxyInstance`. + + .. seealso:: + + :attr:`.AssociationProxyInstance.attr` + + :attr:`.AssociationProxyInstance.local_attr` + + """ + return cast( + "SQLORMOperations[_T]", getattr(self.target_class, self.value_attr) + ) + + @property + def local_attr(self) -> SQLORMOperations[Any]: + """The 'local' class attribute referenced by this + :class:`.AssociationProxyInstance`. + + .. seealso:: + + :attr:`.AssociationProxyInstance.attr` + + :attr:`.AssociationProxyInstance.remote_attr` + + """ + return cast( + "SQLORMOperations[Any]", + getattr(self.owning_class, self.target_collection), + ) + + @property + def attr(self) -> Tuple[SQLORMOperations[Any], SQLORMOperations[_T]]: + """Return a tuple of ``(local_attr, remote_attr)``. + + This attribute was originally intended to facilitate using the + :meth:`_query.Query.join` method to join across the two relationships + at once, however this makes use of a deprecated calling style. + + To use :meth:`_sql.select.join` or :meth:`_orm.Query.join` with + an association proxy, the current method is to make use of the + :attr:`.AssociationProxyInstance.local_attr` and + :attr:`.AssociationProxyInstance.remote_attr` attributes separately:: + + stmt = ( + select(Parent) + .join(Parent.proxied.local_attr) + .join(Parent.proxied.remote_attr) + ) + + A future release may seek to provide a more succinct join pattern + for association proxy attributes. + + .. seealso:: + + :attr:`.AssociationProxyInstance.local_attr` + + :attr:`.AssociationProxyInstance.remote_attr` + + """ + return (self.local_attr, self.remote_attr) + + @util.memoized_property + def scalar(self) -> bool: + """Return ``True`` if this :class:`.AssociationProxyInstance` + proxies a scalar relationship on the local side.""" + + scalar = not self._get_property().uselist + if scalar: + self._initialize_scalar_accessors() + return scalar + + @util.memoized_property + def _value_is_scalar(self) -> bool: + return ( + not self._get_property() + .mapper.get_property(self.value_attr) + .uselist + ) + + @property + def _target_is_object(self) -> bool: + raise NotImplementedError() + + _scalar_get: _GetterProtocol[_T] + _scalar_set: _PlainSetterProtocol[_T] + + def _initialize_scalar_accessors(self) -> None: + if self.parent.getset_factory: + get, set_ = self.parent.getset_factory(None, self) + else: + get, set_ = self.parent._default_getset(None) + self._scalar_get, self._scalar_set = get, cast( + "_PlainSetterProtocol[_T]", set_ + ) + + def _default_getset( + self, collection_class: Any + ) -> Tuple[_GetterProtocol[Any], _SetterProtocol]: + attr = self.value_attr + _getter = operator.attrgetter(attr) + + def getter(instance: Any) -> Optional[_T]: + return _getter(instance) if instance is not None else None + + if collection_class is dict: + + def dict_setter(instance: Any, k: Any, value: _T) -> None: + setattr(instance, attr, value) + + return getter, dict_setter + else: + + def plain_setter(o: Any, v: _T) -> None: + setattr(o, attr, v) + + return getter, plain_setter + + @util.ro_non_memoized_property + def info(self) -> _InfoType: + return self.parent.info + + @overload + def get(self: _Self, obj: Literal[None]) -> _Self: ... + + @overload + def get(self, obj: Any) -> _T: ... + + def get( + self, obj: Any + ) -> Union[Optional[_T], AssociationProxyInstance[_T]]: + if obj is None: + return self + + proxy: _T + + if self.scalar: + target = getattr(obj, self.target_collection) + return self._scalar_get(target) + else: + try: + # If the owning instance is reborn (orm session resurrect, + # etc.), refresh the proxy cache. + creator_id, self_id, proxy = cast( + "Tuple[int, int, _T]", getattr(obj, self.key) + ) + except AttributeError: + pass + else: + if id(obj) == creator_id and id(self) == self_id: + assert self.collection_class is not None + return proxy + + self.collection_class, proxy = self._new( + _lazy_collection(obj, self.target_collection) + ) + setattr(obj, self.key, (id(obj), id(self), proxy)) + return proxy + + def set(self, obj: Any, values: _T) -> None: + if self.scalar: + creator = cast( + "_PlainCreatorProtocol[_T]", + ( + self.parent.creator + if self.parent.creator + else self.target_class + ), + ) + target = getattr(obj, self.target_collection) + if target is None: + if ( + values is None + and not self.parent.create_on_none_assignment + ): + return + setattr(obj, self.target_collection, creator(values)) + else: + self._scalar_set(target, values) + if values is None and self.parent.cascade_scalar_deletes: + setattr(obj, self.target_collection, None) + else: + proxy = self.get(obj) + assert self.collection_class is not None + if proxy is not values: + proxy._bulk_replace(self, values) + + def delete(self, obj: Any) -> None: + if self.owning_class is None: + self._calc_owner(obj, None) + + if self.scalar: + target = getattr(obj, self.target_collection) + if target is not None: + delattr(target, self.value_attr) + delattr(obj, self.target_collection) + + def _new( + self, lazy_collection: _LazyCollectionProtocol[_T] + ) -> Tuple[Type[Any], _T]: + creator = ( + self.parent.creator + if self.parent.creator is not None + else cast("_CreatorProtocol", self.target_class) + ) + collection_class = util.duck_type_collection(lazy_collection()) + + if collection_class is None: + raise exc.InvalidRequestError( + f"lazy collection factory did not return a " + f"valid collection type, got {collection_class}" + ) + if self.parent.proxy_factory: + return ( + collection_class, + self.parent.proxy_factory( + lazy_collection, creator, self.value_attr, self + ), + ) + + if self.parent.getset_factory: + getter, setter = self.parent.getset_factory(collection_class, self) + else: + getter, setter = self.parent._default_getset(collection_class) + + if collection_class is list: + return ( + collection_class, + cast( + _T, + _AssociationList( + lazy_collection, creator, getter, setter, self + ), + ), + ) + elif collection_class is dict: + return ( + collection_class, + cast( + _T, + _AssociationDict( + lazy_collection, creator, getter, setter, self + ), + ), + ) + elif collection_class is set: + return ( + collection_class, + cast( + _T, + _AssociationSet( + lazy_collection, creator, getter, setter, self + ), + ), + ) + else: + raise exc.ArgumentError( + "could not guess which interface to use for " + 'collection_class "%s" backing "%s"; specify a ' + "proxy_factory and proxy_bulk_set manually" + % (self.collection_class, self.target_collection) + ) + + def _set( + self, proxy: _AssociationCollection[Any], values: Iterable[Any] + ) -> None: + if self.parent.proxy_bulk_set: + self.parent.proxy_bulk_set(proxy, values) + elif self.collection_class is list: + cast("_AssociationList[Any]", proxy).extend(values) + elif self.collection_class is dict: + cast("_AssociationDict[Any, Any]", proxy).update(values) + elif self.collection_class is set: + cast("_AssociationSet[Any]", proxy).update(values) + else: + raise exc.ArgumentError( + "no proxy_bulk_set supplied for custom " + "collection_class implementation" + ) + + def _inflate(self, proxy: _AssociationCollection[Any]) -> None: + creator = ( + self.parent.creator + and self.parent.creator + or cast(_CreatorProtocol, self.target_class) + ) + + if self.parent.getset_factory: + getter, setter = self.parent.getset_factory( + self.collection_class, self + ) + else: + getter, setter = self.parent._default_getset(self.collection_class) + + proxy.creator = creator + proxy.getter = getter + proxy.setter = setter + + def _criterion_exists( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: + is_has = kwargs.pop("is_has", None) + + target_assoc = self._unwrap_target_assoc_proxy + if target_assoc is not None: + inner = target_assoc._criterion_exists( + criterion=criterion, **kwargs + ) + return self._comparator._criterion_exists(inner) + + if self._target_is_object: + attr = getattr(self.target_class, self.value_attr) + value_expr = attr.comparator._criterion_exists(criterion, **kwargs) + else: + if kwargs: + raise exc.ArgumentError( + "Can't apply keyword arguments to column-targeted " + "association proxy; use ==" + ) + elif is_has and criterion is not None: + raise exc.ArgumentError( + "Non-empty has() not allowed for " + "column-targeted association proxy; use ==" + ) + + value_expr = criterion + + return self._comparator._criterion_exists(value_expr) + + def any( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: + """Produce a proxied 'any' expression using EXISTS. + + This expression will be a composed product + using the :meth:`.Relationship.Comparator.any` + and/or :meth:`.Relationship.Comparator.has` + operators of the underlying proxied attributes. + + """ + if self._unwrap_target_assoc_proxy is None and ( + self.scalar + and (not self._target_is_object or self._value_is_scalar) + ): + raise exc.InvalidRequestError( + "'any()' not implemented for scalar attributes. Use has()." + ) + return self._criterion_exists( + criterion=criterion, is_has=False, **kwargs + ) + + def has( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: + """Produce a proxied 'has' expression using EXISTS. + + This expression will be a composed product + using the :meth:`.Relationship.Comparator.any` + and/or :meth:`.Relationship.Comparator.has` + operators of the underlying proxied attributes. + + """ + if self._unwrap_target_assoc_proxy is None and ( + not self.scalar + or (self._target_is_object and not self._value_is_scalar) + ): + raise exc.InvalidRequestError( + "'has()' not implemented for collections. Use any()." + ) + return self._criterion_exists( + criterion=criterion, is_has=True, **kwargs + ) + + def __repr__(self) -> str: + return "%s(%r)" % (self.__class__.__name__, self.parent) + + +class AmbiguousAssociationProxyInstance(AssociationProxyInstance[_T]): + """an :class:`.AssociationProxyInstance` where we cannot determine + the type of target object. + """ + + _is_canonical = False + + def _ambiguous(self) -> NoReturn: + raise AttributeError( + "Association proxy %s.%s refers to an attribute '%s' that is not " + "directly mapped on class %s; therefore this operation cannot " + "proceed since we don't know what type of object is referred " + "towards" + % ( + self.owning_class.__name__, + self.target_collection, + self.value_attr, + self.target_class, + ) + ) + + def get(self, obj: Any) -> Any: + if obj is None: + return self + else: + return super().get(obj) + + def __eq__(self, obj: object) -> NoReturn: + self._ambiguous() + + def __ne__(self, obj: object) -> NoReturn: + self._ambiguous() + + def any( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> NoReturn: + self._ambiguous() + + def has( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> NoReturn: + self._ambiguous() + + @util.memoized_property + def _lookup_cache(self) -> Dict[Type[Any], AssociationProxyInstance[_T]]: + # mapping of ->AssociationProxyInstance. + # e.g. proxy is A-> A.b -> B -> B.b_attr, but B.b_attr doesn't exist; + # only B1(B) and B2(B) have "b_attr", keys in here would be B1, B2 + return {} + + def _non_canonical_get_for_object( + self, parent_instance: Any + ) -> AssociationProxyInstance[_T]: + if parent_instance is not None: + actual_obj = getattr(parent_instance, self.target_collection) + if actual_obj is not None: + try: + insp = inspect(actual_obj) + except exc.NoInspectionAvailable: + pass + else: + mapper = insp.mapper + instance_class = mapper.class_ + if instance_class not in self._lookup_cache: + self._populate_cache(instance_class, mapper) + + try: + return self._lookup_cache[instance_class] + except KeyError: + pass + + # no object or ambiguous object given, so return "self", which + # is a proxy with generally only instance-level functionality + return self + + def _populate_cache( + self, instance_class: Any, mapper: Mapper[Any] + ) -> None: + prop = orm.class_mapper(self.owning_class).get_property( + self.target_collection + ) + + if mapper.isa(prop.mapper): + target_class = instance_class + try: + target_assoc = self._cls_unwrap_target_assoc_proxy( + target_class, self.value_attr + ) + except AttributeError: + pass + else: + self._lookup_cache[instance_class] = self._construct_for_assoc( + cast("AssociationProxyInstance[_T]", target_assoc), + self.parent, + self.owning_class, + target_class, + self.value_attr, + ) + + +class ObjectAssociationProxyInstance(AssociationProxyInstance[_T]): + """an :class:`.AssociationProxyInstance` that has an object as a target.""" + + _target_is_object: bool = True + _is_canonical = True + + def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]: + """Produce a proxied 'contains' expression using EXISTS. + + This expression will be a composed product + using the :meth:`.Relationship.Comparator.any`, + :meth:`.Relationship.Comparator.has`, + and/or :meth:`.Relationship.Comparator.contains` + operators of the underlying proxied attributes. + """ + + target_assoc = self._unwrap_target_assoc_proxy + if target_assoc is not None: + return self._comparator._criterion_exists( + target_assoc.contains(other) + if not target_assoc.scalar + else target_assoc == other + ) + elif ( + self._target_is_object + and self.scalar + and not self._value_is_scalar + ): + return self._comparator.has( + getattr(self.target_class, self.value_attr).contains(other) + ) + elif self._target_is_object and self.scalar and self._value_is_scalar: + raise exc.InvalidRequestError( + "contains() doesn't apply to a scalar object endpoint; use ==" + ) + else: + return self._comparator._criterion_exists( + **{self.value_attr: other} + ) + + def __eq__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + # note the has() here will fail for collections; eq_() + # is only allowed with a scalar. + if obj is None: + return or_( + self._comparator.has(**{self.value_attr: obj}), + self._comparator == None, + ) + else: + return self._comparator.has(**{self.value_attr: obj}) + + def __ne__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + # note the has() here will fail for collections; eq_() + # is only allowed with a scalar. + return self._comparator.has( + getattr(self.target_class, self.value_attr) != obj + ) + + +class ColumnAssociationProxyInstance(AssociationProxyInstance[_T]): + """an :class:`.AssociationProxyInstance` that has a database column as a + target. + """ + + _target_is_object: bool = False + _is_canonical = True + + def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + # special case "is None" to check for no related row as well + expr = self._criterion_exists( + self.remote_attr.operate(operators.eq, other) + ) + if other is None: + return or_(expr, self._comparator == None) + else: + return expr + + def operate( + self, op: operators.OperatorType, *other: Any, **kwargs: Any + ) -> ColumnElement[Any]: + return self._criterion_exists( + self.remote_attr.operate(op, *other, **kwargs) + ) + + +class _lazy_collection(_LazyCollectionProtocol[_T]): + def __init__(self, obj: Any, target: str): + self.parent = obj + self.target = target + + def __call__( + self, + ) -> Union[MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T]]: + return getattr(self.parent, self.target) # type: ignore[no-any-return] + + def __getstate__(self) -> Any: + return {"obj": self.parent, "target": self.target} + + def __setstate__(self, state: Any) -> None: + self.parent = state["obj"] + self.target = state["target"] + + +_IT = TypeVar("_IT", bound="Any") +"""instance type - this is the type of object inside a collection. + +this is not the same as the _T of AssociationProxy and +AssociationProxyInstance itself, which will often refer to the +collection[_IT] type. + +""" + + +class _AssociationCollection(Generic[_IT]): + getter: _GetterProtocol[_IT] + """A function. Given an associated object, return the 'value'.""" + + creator: _CreatorProtocol + """ + A function that creates new target entities. Given one parameter: + value. This assertion is assumed:: + + obj = creator(somevalue) + assert getter(obj) == somevalue + """ + + parent: AssociationProxyInstance[_IT] + setter: _SetterProtocol + """A function. Given an associated object and a value, store that + value on the object. + """ + + lazy_collection: _LazyCollectionProtocol[_IT] + """A callable returning a list-based collection of entities (usually an + object attribute managed by a SQLAlchemy relationship())""" + + def __init__( + self, + lazy_collection: _LazyCollectionProtocol[_IT], + creator: _CreatorProtocol, + getter: _GetterProtocol[_IT], + setter: _SetterProtocol, + parent: AssociationProxyInstance[_IT], + ): + """Constructs an _AssociationCollection. + + This will always be a subclass of either _AssociationList, + _AssociationSet, or _AssociationDict. + + """ + self.lazy_collection = lazy_collection + self.creator = creator + self.getter = getter + self.setter = setter + self.parent = parent + + if typing.TYPE_CHECKING: + col: Collection[_IT] + else: + col = property(lambda self: self.lazy_collection()) + + def __len__(self) -> int: + return len(self.col) + + def __bool__(self) -> bool: + return bool(self.col) + + def __getstate__(self) -> Any: + return {"parent": self.parent, "lazy_collection": self.lazy_collection} + + def __setstate__(self, state: Any) -> None: + self.parent = state["parent"] + self.lazy_collection = state["lazy_collection"] + self.parent._inflate(self) + + def clear(self) -> None: + raise NotImplementedError() + + +class _AssociationSingleItem(_AssociationCollection[_T]): + setter: _PlainSetterProtocol[_T] + creator: _PlainCreatorProtocol[_T] + + def _create(self, value: _T) -> Any: + return self.creator(value) + + def _get(self, object_: Any) -> _T: + return self.getter(object_) + + def _bulk_replace( + self, assoc_proxy: AssociationProxyInstance[Any], values: Iterable[_IT] + ) -> None: + self.clear() + assoc_proxy._set(self, values) + + +class _AssociationList(_AssociationSingleItem[_T], MutableSequence[_T]): + """Generic, converting, list-to-list proxy.""" + + col: MutableSequence[_T] + + def _set(self, object_: Any, value: _T) -> None: + self.setter(object_, value) + + @overload + def __getitem__(self, index: int) -> _T: ... + + @overload + def __getitem__(self, index: slice) -> MutableSequence[_T]: ... + + def __getitem__( + self, index: Union[int, slice] + ) -> Union[_T, MutableSequence[_T]]: + if not isinstance(index, slice): + return self._get(self.col[index]) + else: + return [self._get(member) for member in self.col[index]] + + @overload + def __setitem__(self, index: int, value: _T) -> None: ... + + @overload + def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ... + + def __setitem__( + self, index: Union[int, slice], value: Union[_T, Iterable[_T]] + ) -> None: + if not isinstance(index, slice): + self._set(self.col[index], cast("_T", value)) + else: + if index.stop is None: + stop = len(self) + elif index.stop < 0: + stop = len(self) + index.stop + else: + stop = index.stop + step = index.step or 1 + + start = index.start or 0 + rng = list(range(index.start or 0, stop, step)) + + sized_value = list(value) + + if step == 1: + for i in rng: + del self[start] + i = start + for item in sized_value: + self.insert(i, item) + i += 1 + else: + if len(sized_value) != len(rng): + raise ValueError( + "attempt to assign sequence of size %s to " + "extended slice of size %s" + % (len(sized_value), len(rng)) + ) + for i, item in zip(rng, value): + self._set(self.col[i], item) + + @overload + def __delitem__(self, index: int) -> None: ... + + @overload + def __delitem__(self, index: slice) -> None: ... + + def __delitem__(self, index: Union[slice, int]) -> None: + del self.col[index] + + def __contains__(self, value: object) -> bool: + for member in self.col: + # testlib.pragma exempt:__eq__ + if self._get(member) == value: + return True + return False + + def __iter__(self) -> Iterator[_T]: + """Iterate over proxied values. + + For the actual domain objects, iterate over .col instead or + just use the underlying collection directly from its property + on the parent. + """ + + for member in self.col: + yield self._get(member) + return + + def append(self, value: _T) -> None: + col = self.col + item = self._create(value) + col.append(item) + + def count(self, value: Any) -> int: + count = 0 + for v in self: + if v == value: + count += 1 + return count + + def extend(self, values: Iterable[_T]) -> None: + for v in values: + self.append(v) + + def insert(self, index: int, value: _T) -> None: + self.col[index:index] = [self._create(value)] + + def pop(self, index: int = -1) -> _T: + return self.getter(self.col.pop(index)) + + def remove(self, value: _T) -> None: + for i, val in enumerate(self): + if val == value: + del self.col[i] + return + raise ValueError("value not in list") + + def reverse(self) -> NoReturn: + """Not supported, use reversed(mylist)""" + + raise NotImplementedError() + + def sort(self) -> NoReturn: + """Not supported, use sorted(mylist)""" + + raise NotImplementedError() + + def clear(self) -> None: + del self.col[0 : len(self.col)] + + def __eq__(self, other: object) -> bool: + return list(self) == other + + def __ne__(self, other: object) -> bool: + return list(self) != other + + def __lt__(self, other: List[_T]) -> bool: + return list(self) < other + + def __le__(self, other: List[_T]) -> bool: + return list(self) <= other + + def __gt__(self, other: List[_T]) -> bool: + return list(self) > other + + def __ge__(self, other: List[_T]) -> bool: + return list(self) >= other + + def __add__(self, other: List[_T]) -> List[_T]: + try: + other = list(other) + except TypeError: + return NotImplemented + return list(self) + other + + def __radd__(self, other: List[_T]) -> List[_T]: + try: + other = list(other) + except TypeError: + return NotImplemented + return other + list(self) + + def __mul__(self, n: SupportsIndex) -> List[_T]: + if not isinstance(n, int): + return NotImplemented + return list(self) * n + + def __rmul__(self, n: SupportsIndex) -> List[_T]: + if not isinstance(n, int): + return NotImplemented + return n * list(self) + + def __iadd__(self, iterable: Iterable[_T]) -> Self: + self.extend(iterable) + return self + + def __imul__(self, n: SupportsIndex) -> Self: + # unlike a regular list *=, proxied __imul__ will generate unique + # backing objects for each copy. *= on proxied lists is a bit of + # a stretch anyhow, and this interpretation of the __imul__ contract + # is more plausibly useful than copying the backing objects. + if not isinstance(n, int): + raise NotImplementedError() + if n == 0: + self.clear() + elif n > 1: + self.extend(list(self) * (n - 1)) + return self + + if typing.TYPE_CHECKING: + # TODO: no idea how to do this without separate "stub" + def index( + self, value: Any, start: int = ..., stop: int = ... + ) -> int: ... + + else: + + def index(self, value: Any, *arg) -> int: + ls = list(self) + return ls.index(value, *arg) + + def copy(self) -> List[_T]: + return list(self) + + def __repr__(self) -> str: + return repr(list(self)) + + def __hash__(self) -> NoReturn: + raise TypeError("%s objects are unhashable" % type(self).__name__) + + if not typing.TYPE_CHECKING: + for func_name, func in list(locals().items()): + if ( + callable(func) + and func.__name__ == func_name + and not func.__doc__ + and hasattr(list, func_name) + ): + func.__doc__ = getattr(list, func_name).__doc__ + del func_name, func + + +class _AssociationDict(_AssociationCollection[_VT], MutableMapping[_KT, _VT]): + """Generic, converting, dict-to-dict proxy.""" + + setter: _DictSetterProtocol[_VT] + creator: _KeyCreatorProtocol[_VT] + col: MutableMapping[_KT, Optional[_VT]] + + def _create(self, key: _KT, value: Optional[_VT]) -> Any: + return self.creator(key, value) + + def _get(self, object_: Any) -> _VT: + return self.getter(object_) + + def _set(self, object_: Any, key: _KT, value: _VT) -> None: + return self.setter(object_, key, value) + + def __getitem__(self, key: _KT) -> _VT: + return self._get(self.col[key]) + + def __setitem__(self, key: _KT, value: _VT) -> None: + if key in self.col: + self._set(self.col[key], key, value) + else: + self.col[key] = self._create(key, value) + + def __delitem__(self, key: _KT) -> None: + del self.col[key] + + def __contains__(self, key: object) -> bool: + return key in self.col + + def __iter__(self) -> Iterator[_KT]: + return iter(self.col.keys()) + + def clear(self) -> None: + self.col.clear() + + def __eq__(self, other: object) -> bool: + return dict(self) == other + + def __ne__(self, other: object) -> bool: + return dict(self) != other + + def __repr__(self) -> str: + return repr(dict(self)) + + @overload + def get(self, __key: _KT) -> Optional[_VT]: ... + + @overload + def get(self, __key: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ... + + def get( + self, key: _KT, default: Optional[Union[_VT, _T]] = None + ) -> Union[_VT, _T, None]: + try: + return self[key] + except KeyError: + return default + + def setdefault(self, key: _KT, default: Optional[_VT] = None) -> _VT: + # TODO: again, no idea how to create an actual MutableMapping. + # default must allow None, return type can't include None, + # the stub explicitly allows for default of None with a cryptic message + # "This overload should be allowed only if the value type is + # compatible with None.". + if key not in self.col: + self.col[key] = self._create(key, default) + return default # type: ignore + else: + return self[key] + + def keys(self) -> KeysView[_KT]: + return self.col.keys() + + def items(self) -> ItemsView[_KT, _VT]: + return ItemsView(self) + + def values(self) -> ValuesView[_VT]: + return ValuesView(self) + + @overload + def pop(self, __key: _KT) -> _VT: ... + + @overload + def pop( + self, __key: _KT, default: Union[_VT, _T] = ... + ) -> Union[_VT, _T]: ... + + def pop(self, __key: _KT, *arg: Any, **kw: Any) -> Union[_VT, _T]: + member = self.col.pop(__key, *arg, **kw) + return self._get(member) + + def popitem(self) -> Tuple[_KT, _VT]: + item = self.col.popitem() + return (item[0], self._get(item[1])) + + @overload + def update( + self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT + ) -> None: ... + + @overload + def update( + self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT + ) -> None: ... + + @overload + def update(self, **kwargs: _VT) -> None: ... + + def update(self, *a: Any, **kw: Any) -> None: + up: Dict[_KT, _VT] = {} + up.update(*a, **kw) + + for key, value in up.items(): + self[key] = value + + def _bulk_replace( + self, + assoc_proxy: AssociationProxyInstance[Any], + values: Mapping[_KT, _VT], + ) -> None: + existing = set(self) + constants = existing.intersection(values or ()) + additions = set(values or ()).difference(constants) + removals = existing.difference(constants) + + for key, member in values.items() or (): + if key in additions: + self[key] = member + elif key in constants: + self[key] = member + + for key in removals: + del self[key] + + def copy(self) -> Dict[_KT, _VT]: + return dict(self.items()) + + def __hash__(self) -> NoReturn: + raise TypeError("%s objects are unhashable" % type(self).__name__) + + if not typing.TYPE_CHECKING: + for func_name, func in list(locals().items()): + if ( + callable(func) + and func.__name__ == func_name + and not func.__doc__ + and hasattr(dict, func_name) + ): + func.__doc__ = getattr(dict, func_name).__doc__ + del func_name, func + + +class _AssociationSet(_AssociationSingleItem[_T], MutableSet[_T]): + """Generic, converting, set-to-set proxy.""" + + col: MutableSet[_T] + + def __len__(self) -> int: + return len(self.col) + + def __bool__(self) -> bool: + if self.col: + return True + else: + return False + + def __contains__(self, __o: object) -> bool: + for member in self.col: + if self._get(member) == __o: + return True + return False + + def __iter__(self) -> Iterator[_T]: + """Iterate over proxied values. + + For the actual domain objects, iterate over .col instead or just use + the underlying collection directly from its property on the parent. + + """ + for member in self.col: + yield self._get(member) + return + + def add(self, __element: _T) -> None: + if __element not in self: + self.col.add(self._create(__element)) + + # for discard and remove, choosing a more expensive check strategy rather + # than call self.creator() + def discard(self, __element: _T) -> None: + for member in self.col: + if self._get(member) == __element: + self.col.discard(member) + break + + def remove(self, __element: _T) -> None: + for member in self.col: + if self._get(member) == __element: + self.col.discard(member) + return + raise KeyError(__element) + + def pop(self) -> _T: + if not self.col: + raise KeyError("pop from an empty set") + member = self.col.pop() + return self._get(member) + + def update(self, *s: Iterable[_T]) -> None: + for iterable in s: + for value in iterable: + self.add(value) + + def _bulk_replace(self, assoc_proxy: Any, values: Iterable[_T]) -> None: + existing = set(self) + constants = existing.intersection(values or ()) + additions = set(values or ()).difference(constants) + removals = existing.difference(constants) + + appender = self.add + remover = self.remove + + for member in values or (): + if member in additions: + appender(member) + elif member in constants: + appender(member) + + for member in removals: + remover(member) + + def __ior__( # type: ignore + self, other: AbstractSet[_S] + ) -> MutableSet[Union[_T, _S]]: + if not collections._set_binops_check_strict(self, other): + raise NotImplementedError() + for value in other: + self.add(value) + return self + + def _set(self) -> Set[_T]: + return set(iter(self)) + + def union(self, *s: Iterable[_S]) -> MutableSet[Union[_T, _S]]: + return set(self).union(*s) + + def __or__(self, __s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: + return self.union(__s) + + def difference(self, *s: Iterable[Any]) -> MutableSet[_T]: + return set(self).difference(*s) + + def __sub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: + return self.difference(s) + + def difference_update(self, *s: Iterable[Any]) -> None: + for other in s: + for value in other: + self.discard(value) + + def __isub__(self, s: AbstractSet[Any]) -> Self: + if not collections._set_binops_check_strict(self, s): + raise NotImplementedError() + for value in s: + self.discard(value) + return self + + def intersection(self, *s: Iterable[Any]) -> MutableSet[_T]: + return set(self).intersection(*s) + + def __and__(self, s: AbstractSet[Any]) -> MutableSet[_T]: + return self.intersection(s) + + def intersection_update(self, *s: Iterable[Any]) -> None: + for other in s: + want, have = self.intersection(other), set(self) + + remove, add = have - want, want - have + + for value in remove: + self.remove(value) + for value in add: + self.add(value) + + def __iand__(self, s: AbstractSet[Any]) -> Self: + if not collections._set_binops_check_strict(self, s): + raise NotImplementedError() + want = self.intersection(s) + have: Set[_T] = set(self) + + remove, add = have - want, want - have + + for value in remove: + self.remove(value) + for value in add: + self.add(value) + return self + + def symmetric_difference(self, __s: Iterable[_T]) -> MutableSet[_T]: + return set(self).symmetric_difference(__s) + + def __xor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: + return self.symmetric_difference(s) + + def symmetric_difference_update(self, other: Iterable[Any]) -> None: + want, have = self.symmetric_difference(other), set(self) + + remove, add = have - want, want - have + + for value in remove: + self.remove(value) + for value in add: + self.add(value) + + def __ixor__(self, other: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: # type: ignore # noqa: E501 + if not collections._set_binops_check_strict(self, other): + raise NotImplementedError() + + self.symmetric_difference_update(other) + return self + + def issubset(self, __s: Iterable[Any]) -> bool: + return set(self).issubset(__s) + + def issuperset(self, __s: Iterable[Any]) -> bool: + return set(self).issuperset(__s) + + def clear(self) -> None: + self.col.clear() + + def copy(self) -> AbstractSet[_T]: + return set(self) + + def __eq__(self, other: object) -> bool: + return set(self) == other + + def __ne__(self, other: object) -> bool: + return set(self) != other + + def __lt__(self, other: AbstractSet[Any]) -> bool: + return set(self) < other + + def __le__(self, other: AbstractSet[Any]) -> bool: + return set(self) <= other + + def __gt__(self, other: AbstractSet[Any]) -> bool: + return set(self) > other + + def __ge__(self, other: AbstractSet[Any]) -> bool: + return set(self) >= other + + def __repr__(self) -> str: + return repr(set(self)) + + def __hash__(self) -> NoReturn: + raise TypeError("%s objects are unhashable" % type(self).__name__) + + if not typing.TYPE_CHECKING: + for func_name, func in list(locals().items()): + if ( + callable(func) + and func.__name__ == func_name + and not func.__doc__ + and hasattr(set, func_name) + ): + func.__doc__ = getattr(set, func_name).__doc__ + del func_name, func diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/automap.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/automap.py new file mode 100644 index 0000000000000000000000000000000000000000..4064108315c854ef3b75e3cb725905ad7f985153 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/automap.py @@ -0,0 +1,1701 @@ +# ext/automap.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +r"""Define an extension to the :mod:`sqlalchemy.ext.declarative` system +which automatically generates mapped classes and relationships from a database +schema, typically though not necessarily one which is reflected. + +It is hoped that the :class:`.AutomapBase` system provides a quick +and modernized solution to the problem that the very famous +`SQLSoup `_ +also tries to solve, that of generating a quick and rudimentary object +model from an existing database on the fly. By addressing the issue strictly +at the mapper configuration level, and integrating fully with existing +Declarative class techniques, :class:`.AutomapBase` seeks to provide +a well-integrated approach to the issue of expediently auto-generating ad-hoc +mappings. + +.. tip:: The :ref:`automap_toplevel` extension is geared towards a + "zero declaration" approach, where a complete ORM model including classes + and pre-named relationships can be generated on the fly from a database + schema. For applications that still want to use explicit class declarations + including explicit relationship definitions in conjunction with reflection + of tables, the :class:`.DeferredReflection` class, described at + :ref:`orm_declarative_reflected_deferred_reflection`, is a better choice. + +.. _automap_basic_use: + +Basic Use +========= + +The simplest usage is to reflect an existing database into a new model. +We create a new :class:`.AutomapBase` class in a similar manner as to how +we create a declarative base class, using :func:`.automap_base`. +We then call :meth:`.AutomapBase.prepare` on the resulting base class, +asking it to reflect the schema and produce mappings:: + + from sqlalchemy.ext.automap import automap_base + from sqlalchemy.orm import Session + from sqlalchemy import create_engine + + Base = automap_base() + + # engine, suppose it has two tables 'user' and 'address' set up + engine = create_engine("sqlite:///mydatabase.db") + + # reflect the tables + Base.prepare(autoload_with=engine) + + # mapped classes are now created with names by default + # matching that of the table name. + User = Base.classes.user + Address = Base.classes.address + + session = Session(engine) + + # rudimentary relationships are produced + session.add(Address(email_address="foo@bar.com", user=User(name="foo"))) + session.commit() + + # collection-based relationships are by default named + # "_collection" + u1 = session.query(User).first() + print(u1.address_collection) + +Above, calling :meth:`.AutomapBase.prepare` while passing along the +:paramref:`.AutomapBase.prepare.reflect` parameter indicates that the +:meth:`_schema.MetaData.reflect` +method will be called on this declarative base +classes' :class:`_schema.MetaData` collection; then, each **viable** +:class:`_schema.Table` within the :class:`_schema.MetaData` +will get a new mapped class +generated automatically. The :class:`_schema.ForeignKeyConstraint` +objects which +link the various tables together will be used to produce new, bidirectional +:func:`_orm.relationship` objects between classes. +The classes and relationships +follow along a default naming scheme that we can customize. At this point, +our basic mapping consisting of related ``User`` and ``Address`` classes is +ready to use in the traditional way. + +.. note:: By **viable**, we mean that for a table to be mapped, it must + specify a primary key. Additionally, if the table is detected as being + a pure association table between two other tables, it will not be directly + mapped and will instead be configured as a many-to-many table between + the mappings for the two referring tables. + +Generating Mappings from an Existing MetaData +============================================= + +We can pass a pre-declared :class:`_schema.MetaData` object to +:func:`.automap_base`. +This object can be constructed in any way, including programmatically, from +a serialized file, or from itself being reflected using +:meth:`_schema.MetaData.reflect`. +Below we illustrate a combination of reflection and +explicit table declaration:: + + from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey + from sqlalchemy.ext.automap import automap_base + + engine = create_engine("sqlite:///mydatabase.db") + + # produce our own MetaData object + metadata = MetaData() + + # we can reflect it ourselves from a database, using options + # such as 'only' to limit what tables we look at... + metadata.reflect(engine, only=["user", "address"]) + + # ... or just define our own Table objects with it (or combine both) + Table( + "user_order", + metadata, + Column("id", Integer, primary_key=True), + Column("user_id", ForeignKey("user.id")), + ) + + # we can then produce a set of mappings from this MetaData. + Base = automap_base(metadata=metadata) + + # calling prepare() just sets up mapped classes and relationships. + Base.prepare() + + # mapped classes are ready + User = Base.classes.user + Address = Base.classes.address + Order = Base.classes.user_order + +.. _automap_by_module: + +Generating Mappings from Multiple Schemas +========================================= + +The :meth:`.AutomapBase.prepare` method when used with reflection may reflect +tables from one schema at a time at most, using the +:paramref:`.AutomapBase.prepare.schema` parameter to indicate the name of a +schema to be reflected from. In order to populate the :class:`.AutomapBase` +with tables from multiple schemas, :meth:`.AutomapBase.prepare` may be invoked +multiple times, each time passing a different name to the +:paramref:`.AutomapBase.prepare.schema` parameter. The +:meth:`.AutomapBase.prepare` method keeps an internal list of +:class:`_schema.Table` objects that have already been mapped, and will add new +mappings only for those :class:`_schema.Table` objects that are new since the +last time :meth:`.AutomapBase.prepare` was run:: + + e = create_engine("postgresql://scott:tiger@localhost/test") + + Base.metadata.create_all(e) + + Base = automap_base() + + Base.prepare(e) + Base.prepare(e, schema="test_schema") + Base.prepare(e, schema="test_schema_2") + +.. versionadded:: 2.0 The :meth:`.AutomapBase.prepare` method may be called + any number of times; only newly added tables will be mapped + on each run. Previously in version 1.4 and earlier, multiple calls would + cause errors as it would attempt to re-map an already mapped class. + The previous workaround approach of invoking + :meth:`_schema.MetaData.reflect` directly remains available as well. + +Automapping same-named tables across multiple schemas +----------------------------------------------------- + +For the common case where multiple schemas may have same-named tables and +therefore would generate same-named classes, conflicts can be resolved either +through use of the :paramref:`.AutomapBase.prepare.classname_for_table` hook to +apply different classnames on a per-schema basis, or by using the +:paramref:`.AutomapBase.prepare.modulename_for_table` hook, which allows +disambiguation of same-named classes by changing their effective ``__module__`` +attribute. In the example below, this hook is used to create a ``__module__`` +attribute for all classes that is of the form ``mymodule.``, where +the schema name ``default`` is used if no schema is present:: + + e = create_engine("postgresql://scott:tiger@localhost/test") + + Base.metadata.create_all(e) + + + def module_name_for_table(cls, tablename, table): + if table.schema is not None: + return f"mymodule.{table.schema}" + else: + return f"mymodule.default" + + + Base = automap_base() + + Base.prepare(e, modulename_for_table=module_name_for_table) + Base.prepare( + e, schema="test_schema", modulename_for_table=module_name_for_table + ) + Base.prepare( + e, schema="test_schema_2", modulename_for_table=module_name_for_table + ) + +The same named-classes are organized into a hierarchical collection available +at :attr:`.AutomapBase.by_module`. This collection is traversed using the +dot-separated name of a particular package/module down into the desired +class name. + +.. note:: When using the :paramref:`.AutomapBase.prepare.modulename_for_table` + hook to return a new ``__module__`` that is not ``None``, the class is + **not** placed into the :attr:`.AutomapBase.classes` collection; only + classes that were not given an explicit modulename are placed here, as the + collection cannot represent same-named classes individually. + +In the example above, if the database contained a table named ``accounts`` in +all three of the default schema, the ``test_schema`` schema, and the +``test_schema_2`` schema, three separate classes will be available as:: + + Base.by_module.mymodule.default.accounts + Base.by_module.mymodule.test_schema.accounts + Base.by_module.mymodule.test_schema_2.accounts + +The default module namespace generated for all :class:`.AutomapBase` classes is +``sqlalchemy.ext.automap``. If no +:paramref:`.AutomapBase.prepare.modulename_for_table` hook is used, the +contents of :attr:`.AutomapBase.by_module` will be entirely within the +``sqlalchemy.ext.automap`` namespace (e.g. +``MyBase.by_module.sqlalchemy.ext.automap.``), which would contain +the same series of classes as what would be seen in +:attr:`.AutomapBase.classes`. Therefore it's generally only necessary to use +:attr:`.AutomapBase.by_module` when explicit ``__module__`` conventions are +present. + +.. versionadded: 2.0 + + Added the :attr:`.AutomapBase.by_module` collection, which stores + classes within a named hierarchy based on dot-separated module names, + as well as the :paramref:`.Automap.prepare.modulename_for_table` parameter + which allows for custom ``__module__`` schemes for automapped + classes. + + + +Specifying Classes Explicitly +============================= + +.. tip:: If explicit classes are expected to be prominent in an application, + consider using :class:`.DeferredReflection` instead. + +The :mod:`.sqlalchemy.ext.automap` extension allows classes to be defined +explicitly, in a way similar to that of the :class:`.DeferredReflection` class. +Classes that extend from :class:`.AutomapBase` act like regular declarative +classes, but are not immediately mapped after their construction, and are +instead mapped when we call :meth:`.AutomapBase.prepare`. The +:meth:`.AutomapBase.prepare` method will make use of the classes we've +established based on the table name we use. If our schema contains tables +``user`` and ``address``, we can define one or both of the classes to be used:: + + from sqlalchemy.ext.automap import automap_base + from sqlalchemy import create_engine + + # automap base + Base = automap_base() + + + # pre-declare User for the 'user' table + class User(Base): + __tablename__ = "user" + + # override schema elements like Columns + user_name = Column("name", String) + + # override relationships too, if desired. + # we must use the same name that automap would use for the + # relationship, and also must refer to the class name that automap will + # generate for "address" + address_collection = relationship("address", collection_class=set) + + + # reflect + engine = create_engine("sqlite:///mydatabase.db") + Base.prepare(autoload_with=engine) + + # we still have Address generated from the tablename "address", + # but User is the same as Base.classes.User now + + Address = Base.classes.address + + u1 = session.query(User).first() + print(u1.address_collection) + + # the backref is still there: + a1 = session.query(Address).first() + print(a1.user) + +Above, one of the more intricate details is that we illustrated overriding +one of the :func:`_orm.relationship` objects that automap would have created. +To do this, we needed to make sure the names match up with what automap +would normally generate, in that the relationship name would be +``User.address_collection`` and the name of the class referred to, from +automap's perspective, is called ``address``, even though we are referring to +it as ``Address`` within our usage of this class. + +Overriding Naming Schemes +========================= + +:mod:`.sqlalchemy.ext.automap` is tasked with producing mapped classes and +relationship names based on a schema, which means it has decision points in how +these names are determined. These three decision points are provided using +functions which can be passed to the :meth:`.AutomapBase.prepare` method, and +are known as :func:`.classname_for_table`, +:func:`.name_for_scalar_relationship`, +and :func:`.name_for_collection_relationship`. Any or all of these +functions are provided as in the example below, where we use a "camel case" +scheme for class names and a "pluralizer" for collection names using the +`Inflect `_ package:: + + import re + import inflect + + + def camelize_classname(base, tablename, table): + "Produce a 'camelized' class name, e.g." + "'words_and_underscores' -> 'WordsAndUnderscores'" + + return str( + tablename[0].upper() + + re.sub( + r"_([a-z])", + lambda m: m.group(1).upper(), + tablename[1:], + ) + ) + + + _pluralizer = inflect.engine() + + + def pluralize_collection(base, local_cls, referred_cls, constraint): + "Produce an 'uncamelized', 'pluralized' class name, e.g." + "'SomeTerm' -> 'some_terms'" + + referred_name = referred_cls.__name__ + uncamelized = re.sub( + r"[A-Z]", + lambda m: "_%s" % m.group(0).lower(), + referred_name, + )[1:] + pluralized = _pluralizer.plural(uncamelized) + return pluralized + + + from sqlalchemy.ext.automap import automap_base + + Base = automap_base() + + engine = create_engine("sqlite:///mydatabase.db") + + Base.prepare( + autoload_with=engine, + classname_for_table=camelize_classname, + name_for_collection_relationship=pluralize_collection, + ) + +From the above mapping, we would now have classes ``User`` and ``Address``, +where the collection from ``User`` to ``Address`` is called +``User.addresses``:: + + User, Address = Base.classes.User, Base.classes.Address + + u1 = User(addresses=[Address(email="foo@bar.com")]) + +Relationship Detection +====================== + +The vast majority of what automap accomplishes is the generation of +:func:`_orm.relationship` structures based on foreign keys. The mechanism +by which this works for many-to-one and one-to-many relationships is as +follows: + +1. A given :class:`_schema.Table`, known to be mapped to a particular class, + is examined for :class:`_schema.ForeignKeyConstraint` objects. + +2. From each :class:`_schema.ForeignKeyConstraint`, the remote + :class:`_schema.Table` + object present is matched up to the class to which it is to be mapped, + if any, else it is skipped. + +3. As the :class:`_schema.ForeignKeyConstraint` + we are examining corresponds to a + reference from the immediate mapped class, the relationship will be set up + as a many-to-one referring to the referred class; a corresponding + one-to-many backref will be created on the referred class referring + to this class. + +4. If any of the columns that are part of the + :class:`_schema.ForeignKeyConstraint` + are not nullable (e.g. ``nullable=False``), a + :paramref:`_orm.relationship.cascade` keyword argument + of ``all, delete-orphan`` will be added to the keyword arguments to + be passed to the relationship or backref. If the + :class:`_schema.ForeignKeyConstraint` reports that + :paramref:`_schema.ForeignKeyConstraint.ondelete` + is set to ``CASCADE`` for a not null or ``SET NULL`` for a nullable + set of columns, the option :paramref:`_orm.relationship.passive_deletes` + flag is set to ``True`` in the set of relationship keyword arguments. + Note that not all backends support reflection of ON DELETE. + +5. The names of the relationships are determined using the + :paramref:`.AutomapBase.prepare.name_for_scalar_relationship` and + :paramref:`.AutomapBase.prepare.name_for_collection_relationship` + callable functions. It is important to note that the default relationship + naming derives the name from the **the actual class name**. If you've + given a particular class an explicit name by declaring it, or specified an + alternate class naming scheme, that's the name from which the relationship + name will be derived. + +6. The classes are inspected for an existing mapped property matching these + names. If one is detected on one side, but none on the other side, + :class:`.AutomapBase` attempts to create a relationship on the missing side, + then uses the :paramref:`_orm.relationship.back_populates` + parameter in order to + point the new relationship to the other side. + +7. In the usual case where no relationship is on either side, + :meth:`.AutomapBase.prepare` produces a :func:`_orm.relationship` on the + "many-to-one" side and matches it to the other using the + :paramref:`_orm.relationship.backref` parameter. + +8. Production of the :func:`_orm.relationship` and optionally the + :func:`.backref` + is handed off to the :paramref:`.AutomapBase.prepare.generate_relationship` + function, which can be supplied by the end-user in order to augment + the arguments passed to :func:`_orm.relationship` or :func:`.backref` or to + make use of custom implementations of these functions. + +Custom Relationship Arguments +----------------------------- + +The :paramref:`.AutomapBase.prepare.generate_relationship` hook can be used +to add parameters to relationships. For most cases, we can make use of the +existing :func:`.automap.generate_relationship` function to return +the object, after augmenting the given keyword dictionary with our own +arguments. + +Below is an illustration of how to send +:paramref:`_orm.relationship.cascade` and +:paramref:`_orm.relationship.passive_deletes` +options along to all one-to-many relationships:: + + from sqlalchemy.ext.automap import generate_relationship + from sqlalchemy.orm import interfaces + + + def _gen_relationship( + base, direction, return_fn, attrname, local_cls, referred_cls, **kw + ): + if direction is interfaces.ONETOMANY: + kw["cascade"] = "all, delete-orphan" + kw["passive_deletes"] = True + # make use of the built-in function to actually return + # the result. + return generate_relationship( + base, direction, return_fn, attrname, local_cls, referred_cls, **kw + ) + + + from sqlalchemy.ext.automap import automap_base + from sqlalchemy import create_engine + + # automap base + Base = automap_base() + + engine = create_engine("sqlite:///mydatabase.db") + Base.prepare(autoload_with=engine, generate_relationship=_gen_relationship) + +Many-to-Many relationships +-------------------------- + +:mod:`.sqlalchemy.ext.automap` will generate many-to-many relationships, e.g. +those which contain a ``secondary`` argument. The process for producing these +is as follows: + +1. A given :class:`_schema.Table` is examined for + :class:`_schema.ForeignKeyConstraint` + objects, before any mapped class has been assigned to it. + +2. If the table contains two and exactly two + :class:`_schema.ForeignKeyConstraint` + objects, and all columns within this table are members of these two + :class:`_schema.ForeignKeyConstraint` objects, the table is assumed to be a + "secondary" table, and will **not be mapped directly**. + +3. The two (or one, for self-referential) external tables to which the + :class:`_schema.Table` + refers to are matched to the classes to which they will be + mapped, if any. + +4. If mapped classes for both sides are located, a many-to-many bi-directional + :func:`_orm.relationship` / :func:`.backref` + pair is created between the two + classes. + +5. The override logic for many-to-many works the same as that of one-to-many/ + many-to-one; the :func:`.generate_relationship` function is called upon + to generate the structures and existing attributes will be maintained. + +Relationships with Inheritance +------------------------------ + +:mod:`.sqlalchemy.ext.automap` will not generate any relationships between +two classes that are in an inheritance relationship. That is, with two +classes given as follows:: + + class Employee(Base): + __tablename__ = "employee" + id = Column(Integer, primary_key=True) + type = Column(String(50)) + __mapper_args__ = { + "polymorphic_identity": "employee", + "polymorphic_on": type, + } + + + class Engineer(Employee): + __tablename__ = "engineer" + id = Column(Integer, ForeignKey("employee.id"), primary_key=True) + __mapper_args__ = { + "polymorphic_identity": "engineer", + } + +The foreign key from ``Engineer`` to ``Employee`` is used not for a +relationship, but to establish joined inheritance between the two classes. + +Note that this means automap will not generate *any* relationships +for foreign keys that link from a subclass to a superclass. If a mapping +has actual relationships from subclass to superclass as well, those +need to be explicit. Below, as we have two separate foreign keys +from ``Engineer`` to ``Employee``, we need to set up both the relationship +we want as well as the ``inherit_condition``, as these are not things +SQLAlchemy can guess:: + + class Employee(Base): + __tablename__ = "employee" + id = Column(Integer, primary_key=True) + type = Column(String(50)) + + __mapper_args__ = { + "polymorphic_identity": "employee", + "polymorphic_on": type, + } + + + class Engineer(Employee): + __tablename__ = "engineer" + id = Column(Integer, ForeignKey("employee.id"), primary_key=True) + favorite_employee_id = Column(Integer, ForeignKey("employee.id")) + + favorite_employee = relationship( + Employee, foreign_keys=favorite_employee_id + ) + + __mapper_args__ = { + "polymorphic_identity": "engineer", + "inherit_condition": id == Employee.id, + } + +Handling Simple Naming Conflicts +-------------------------------- + +In the case of naming conflicts during mapping, override any of +:func:`.classname_for_table`, :func:`.name_for_scalar_relationship`, +and :func:`.name_for_collection_relationship` as needed. For example, if +automap is attempting to name a many-to-one relationship the same as an +existing column, an alternate convention can be conditionally selected. Given +a schema: + +.. sourcecode:: sql + + CREATE TABLE table_a ( + id INTEGER PRIMARY KEY + ); + + CREATE TABLE table_b ( + id INTEGER PRIMARY KEY, + table_a INTEGER, + FOREIGN KEY(table_a) REFERENCES table_a(id) + ); + +The above schema will first automap the ``table_a`` table as a class named +``table_a``; it will then automap a relationship onto the class for ``table_b`` +with the same name as this related class, e.g. ``table_a``. This +relationship name conflicts with the mapping column ``table_b.table_a``, +and will emit an error on mapping. + +We can resolve this conflict by using an underscore as follows:: + + def name_for_scalar_relationship( + base, local_cls, referred_cls, constraint + ): + name = referred_cls.__name__.lower() + local_table = local_cls.__table__ + if name in local_table.columns: + newname = name + "_" + warnings.warn( + "Already detected name %s present. using %s" % (name, newname) + ) + return newname + return name + + + Base.prepare( + autoload_with=engine, + name_for_scalar_relationship=name_for_scalar_relationship, + ) + +Alternatively, we can change the name on the column side. The columns +that are mapped can be modified using the technique described at +:ref:`mapper_column_distinct_names`, by assigning the column explicitly +to a new name:: + + Base = automap_base() + + + class TableB(Base): + __tablename__ = "table_b" + _table_a = Column("table_a", ForeignKey("table_a.id")) + + + Base.prepare(autoload_with=engine) + +Using Automap with Explicit Declarations +======================================== + +As noted previously, automap has no dependency on reflection, and can make +use of any collection of :class:`_schema.Table` objects within a +:class:`_schema.MetaData` +collection. From this, it follows that automap can also be used +generate missing relationships given an otherwise complete model that fully +defines table metadata:: + + from sqlalchemy.ext.automap import automap_base + from sqlalchemy import Column, Integer, String, ForeignKey + + Base = automap_base() + + + class User(Base): + __tablename__ = "user" + + id = Column(Integer, primary_key=True) + name = Column(String) + + + class Address(Base): + __tablename__ = "address" + + id = Column(Integer, primary_key=True) + email = Column(String) + user_id = Column(ForeignKey("user.id")) + + + # produce relationships + Base.prepare() + + # mapping is complete, with "address_collection" and + # "user" relationships + a1 = Address(email="u1") + a2 = Address(email="u2") + u1 = User(address_collection=[a1, a2]) + assert a1.user is u1 + +Above, given mostly complete ``User`` and ``Address`` mappings, the +:class:`_schema.ForeignKey` which we defined on ``Address.user_id`` allowed a +bidirectional relationship pair ``Address.user`` and +``User.address_collection`` to be generated on the mapped classes. + +Note that when subclassing :class:`.AutomapBase`, +the :meth:`.AutomapBase.prepare` method is required; if not called, the classes +we've declared are in an un-mapped state. + + +.. _automap_intercepting_columns: + +Intercepting Column Definitions +=============================== + +The :class:`_schema.MetaData` and :class:`_schema.Table` objects support an +event hook :meth:`_events.DDLEvents.column_reflect` that may be used to intercept +the information reflected about a database column before the :class:`_schema.Column` +object is constructed. For example if we wanted to map columns using a +naming convention such as ``"attr_"``, the event could +be applied as:: + + @event.listens_for(Base.metadata, "column_reflect") + def column_reflect(inspector, table, column_info): + # set column.key = "attr_" + column_info["key"] = "attr_%s" % column_info["name"].lower() + + + # run reflection + Base.prepare(autoload_with=engine) + +.. versionadded:: 1.4.0b2 the :meth:`_events.DDLEvents.column_reflect` event + may be applied to a :class:`_schema.MetaData` object. + +.. seealso:: + + :meth:`_events.DDLEvents.column_reflect` + + :ref:`mapper_automated_reflection_schemes` - in the ORM mapping documentation + + +""" # noqa +from __future__ import annotations + +import dataclasses +from typing import Any +from typing import Callable +from typing import cast +from typing import ClassVar +from typing import Dict +from typing import List +from typing import NoReturn +from typing import Optional +from typing import overload +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .. import util +from ..orm import backref +from ..orm import declarative_base as _declarative_base +from ..orm import exc as orm_exc +from ..orm import interfaces +from ..orm import relationship +from ..orm.decl_base import _DeferredMapperConfig +from ..orm.mapper import _CONFIGURE_MUTEX +from ..schema import ForeignKeyConstraint +from ..sql import and_ +from ..util import Properties +from ..util.typing import Protocol + +if TYPE_CHECKING: + from ..engine.base import Engine + from ..orm.base import RelationshipDirection + from ..orm.relationships import ORMBackrefArgument + from ..orm.relationships import Relationship + from ..sql.schema import Column + from ..sql.schema import MetaData + from ..sql.schema import Table + from ..util import immutabledict + + +_KT = TypeVar("_KT", bound=Any) +_VT = TypeVar("_VT", bound=Any) + + +class PythonNameForTableType(Protocol): + def __call__( + self, base: Type[Any], tablename: str, table: Table + ) -> str: ... + + +def classname_for_table( + base: Type[Any], + tablename: str, + table: Table, +) -> str: + """Return the class name that should be used, given the name + of a table. + + The default implementation is:: + + return str(tablename) + + Alternate implementations can be specified using the + :paramref:`.AutomapBase.prepare.classname_for_table` + parameter. + + :param base: the :class:`.AutomapBase` class doing the prepare. + + :param tablename: string name of the :class:`_schema.Table`. + + :param table: the :class:`_schema.Table` object itself. + + :return: a string class name. + + .. note:: + + In Python 2, the string used for the class name **must** be a + non-Unicode object, e.g. a ``str()`` object. The ``.name`` attribute + of :class:`_schema.Table` is typically a Python unicode subclass, + so the + ``str()`` function should be applied to this name, after accounting for + any non-ASCII characters. + + """ + return str(tablename) + + +class NameForScalarRelationshipType(Protocol): + def __call__( + self, + base: Type[Any], + local_cls: Type[Any], + referred_cls: Type[Any], + constraint: ForeignKeyConstraint, + ) -> str: ... + + +def name_for_scalar_relationship( + base: Type[Any], + local_cls: Type[Any], + referred_cls: Type[Any], + constraint: ForeignKeyConstraint, +) -> str: + """Return the attribute name that should be used to refer from one + class to another, for a scalar object reference. + + The default implementation is:: + + return referred_cls.__name__.lower() + + Alternate implementations can be specified using the + :paramref:`.AutomapBase.prepare.name_for_scalar_relationship` + parameter. + + :param base: the :class:`.AutomapBase` class doing the prepare. + + :param local_cls: the class to be mapped on the local side. + + :param referred_cls: the class to be mapped on the referring side. + + :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being + inspected to produce this relationship. + + """ + return referred_cls.__name__.lower() + + +class NameForCollectionRelationshipType(Protocol): + def __call__( + self, + base: Type[Any], + local_cls: Type[Any], + referred_cls: Type[Any], + constraint: ForeignKeyConstraint, + ) -> str: ... + + +def name_for_collection_relationship( + base: Type[Any], + local_cls: Type[Any], + referred_cls: Type[Any], + constraint: ForeignKeyConstraint, +) -> str: + """Return the attribute name that should be used to refer from one + class to another, for a collection reference. + + The default implementation is:: + + return referred_cls.__name__.lower() + "_collection" + + Alternate implementations + can be specified using the + :paramref:`.AutomapBase.prepare.name_for_collection_relationship` + parameter. + + :param base: the :class:`.AutomapBase` class doing the prepare. + + :param local_cls: the class to be mapped on the local side. + + :param referred_cls: the class to be mapped on the referring side. + + :param constraint: the :class:`_schema.ForeignKeyConstraint` that is being + inspected to produce this relationship. + + """ + return referred_cls.__name__.lower() + "_collection" + + +class GenerateRelationshipType(Protocol): + @overload + def __call__( + self, + base: Type[Any], + direction: RelationshipDirection, + return_fn: Callable[..., Relationship[Any]], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, + ) -> Relationship[Any]: ... + + @overload + def __call__( + self, + base: Type[Any], + direction: RelationshipDirection, + return_fn: Callable[..., ORMBackrefArgument], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, + ) -> ORMBackrefArgument: ... + + def __call__( + self, + base: Type[Any], + direction: RelationshipDirection, + return_fn: Union[ + Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument] + ], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, + ) -> Union[ORMBackrefArgument, Relationship[Any]]: ... + + +@overload +def generate_relationship( + base: Type[Any], + direction: RelationshipDirection, + return_fn: Callable[..., Relationship[Any]], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, +) -> Relationship[Any]: ... + + +@overload +def generate_relationship( + base: Type[Any], + direction: RelationshipDirection, + return_fn: Callable[..., ORMBackrefArgument], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, +) -> ORMBackrefArgument: ... + + +def generate_relationship( + base: Type[Any], + direction: RelationshipDirection, + return_fn: Union[ + Callable[..., Relationship[Any]], Callable[..., ORMBackrefArgument] + ], + attrname: str, + local_cls: Type[Any], + referred_cls: Type[Any], + **kw: Any, +) -> Union[Relationship[Any], ORMBackrefArgument]: + r"""Generate a :func:`_orm.relationship` or :func:`.backref` + on behalf of two + mapped classes. + + An alternate implementation of this function can be specified using the + :paramref:`.AutomapBase.prepare.generate_relationship` parameter. + + The default implementation of this function is as follows:: + + if return_fn is backref: + return return_fn(attrname, **kw) + elif return_fn is relationship: + return return_fn(referred_cls, **kw) + else: + raise TypeError("Unknown relationship function: %s" % return_fn) + + :param base: the :class:`.AutomapBase` class doing the prepare. + + :param direction: indicate the "direction" of the relationship; this will + be one of :data:`.ONETOMANY`, :data:`.MANYTOONE`, :data:`.MANYTOMANY`. + + :param return_fn: the function that is used by default to create the + relationship. This will be either :func:`_orm.relationship` or + :func:`.backref`. The :func:`.backref` function's result will be used to + produce a new :func:`_orm.relationship` in a second step, + so it is critical + that user-defined implementations correctly differentiate between the two + functions, if a custom relationship function is being used. + + :param attrname: the attribute name to which this relationship is being + assigned. If the value of :paramref:`.generate_relationship.return_fn` is + the :func:`.backref` function, then this name is the name that is being + assigned to the backref. + + :param local_cls: the "local" class to which this relationship or backref + will be locally present. + + :param referred_cls: the "referred" class to which the relationship or + backref refers to. + + :param \**kw: all additional keyword arguments are passed along to the + function. + + :return: a :func:`_orm.relationship` or :func:`.backref` construct, + as dictated + by the :paramref:`.generate_relationship.return_fn` parameter. + + """ + + if return_fn is backref: + return return_fn(attrname, **kw) + elif return_fn is relationship: + return return_fn(referred_cls, **kw) + else: + raise TypeError("Unknown relationship function: %s" % return_fn) + + +ByModuleProperties = Properties[Union["ByModuleProperties", Type[Any]]] + + +class AutomapBase: + """Base class for an "automap" schema. + + The :class:`.AutomapBase` class can be compared to the "declarative base" + class that is produced by the :func:`.declarative.declarative_base` + function. In practice, the :class:`.AutomapBase` class is always used + as a mixin along with an actual declarative base. + + A new subclassable :class:`.AutomapBase` is typically instantiated + using the :func:`.automap_base` function. + + .. seealso:: + + :ref:`automap_toplevel` + + """ + + __abstract__ = True + + classes: ClassVar[Properties[Type[Any]]] + """An instance of :class:`.util.Properties` containing classes. + + This object behaves much like the ``.c`` collection on a table. Classes + are present under the name they were given, e.g.:: + + Base = automap_base() + Base.prepare(autoload_with=some_engine) + + User, Address = Base.classes.User, Base.classes.Address + + For class names that overlap with a method name of + :class:`.util.Properties`, such as ``items()``, the getitem form + is also supported:: + + Item = Base.classes["items"] + + """ + + by_module: ClassVar[ByModuleProperties] + """An instance of :class:`.util.Properties` containing a hierarchal + structure of dot-separated module names linked to classes. + + This collection is an alternative to the :attr:`.AutomapBase.classes` + collection that is useful when making use of the + :paramref:`.AutomapBase.prepare.modulename_for_table` parameter, which will + apply distinct ``__module__`` attributes to generated classes. + + The default ``__module__`` an automap-generated class is + ``sqlalchemy.ext.automap``; to access this namespace using + :attr:`.AutomapBase.by_module` looks like:: + + User = Base.by_module.sqlalchemy.ext.automap.User + + If a class had a ``__module__`` of ``mymodule.account``, accessing + this namespace looks like:: + + MyClass = Base.by_module.mymodule.account.MyClass + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`automap_by_module` + + """ + + metadata: ClassVar[MetaData] + """Refers to the :class:`_schema.MetaData` collection that will be used + for new :class:`_schema.Table` objects. + + .. seealso:: + + :ref:`orm_declarative_metadata` + + """ + + _sa_automapbase_bookkeeping: ClassVar[_Bookkeeping] + + @classmethod + @util.deprecated_params( + engine=( + "2.0", + "The :paramref:`_automap.AutomapBase.prepare.engine` parameter " + "is deprecated and will be removed in a future release. " + "Please use the " + ":paramref:`_automap.AutomapBase.prepare.autoload_with` " + "parameter.", + ), + reflect=( + "2.0", + "The :paramref:`_automap.AutomapBase.prepare.reflect` " + "parameter is deprecated and will be removed in a future " + "release. Reflection is enabled when " + ":paramref:`_automap.AutomapBase.prepare.autoload_with` " + "is passed.", + ), + ) + def prepare( + cls: Type[AutomapBase], + autoload_with: Optional[Engine] = None, + engine: Optional[Any] = None, + reflect: bool = False, + schema: Optional[str] = None, + classname_for_table: Optional[PythonNameForTableType] = None, + modulename_for_table: Optional[PythonNameForTableType] = None, + collection_class: Optional[Any] = None, + name_for_scalar_relationship: Optional[ + NameForScalarRelationshipType + ] = None, + name_for_collection_relationship: Optional[ + NameForCollectionRelationshipType + ] = None, + generate_relationship: Optional[GenerateRelationshipType] = None, + reflection_options: Union[ + Dict[_KT, _VT], immutabledict[_KT, _VT] + ] = util.EMPTY_DICT, + ) -> None: + """Extract mapped classes and relationships from the + :class:`_schema.MetaData` and perform mappings. + + For full documentation and examples see + :ref:`automap_basic_use`. + + :param autoload_with: an :class:`_engine.Engine` or + :class:`_engine.Connection` with which + to perform schema reflection; when specified, the + :meth:`_schema.MetaData.reflect` method will be invoked within + the scope of this method. + + :param engine: legacy; use :paramref:`.AutomapBase.autoload_with`. + Used to indicate the :class:`_engine.Engine` or + :class:`_engine.Connection` with which to reflect tables with, + if :paramref:`.AutomapBase.reflect` is True. + + :param reflect: legacy; use :paramref:`.AutomapBase.autoload_with`. + Indicates that :meth:`_schema.MetaData.reflect` should be invoked. + + :param classname_for_table: callable function which will be used to + produce new class names, given a table name. Defaults to + :func:`.classname_for_table`. + + :param modulename_for_table: callable function which will be used to + produce the effective ``__module__`` for an internally generated + class, to allow for multiple classes of the same name in a single + automap base which would be in different "modules". + + Defaults to ``None``, which will indicate that ``__module__`` will not + be set explicitly; the Python runtime will use the value + ``sqlalchemy.ext.automap`` for these classes. + + When assigning ``__module__`` to generated classes, they can be + accessed based on dot-separated module names using the + :attr:`.AutomapBase.by_module` collection. Classes that have + an explicit ``__module_`` assigned using this hook do **not** get + placed into the :attr:`.AutomapBase.classes` collection, only + into :attr:`.AutomapBase.by_module`. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`automap_by_module` + + :param name_for_scalar_relationship: callable function which will be + used to produce relationship names for scalar relationships. Defaults + to :func:`.name_for_scalar_relationship`. + + :param name_for_collection_relationship: callable function which will + be used to produce relationship names for collection-oriented + relationships. Defaults to :func:`.name_for_collection_relationship`. + + :param generate_relationship: callable function which will be used to + actually generate :func:`_orm.relationship` and :func:`.backref` + constructs. Defaults to :func:`.generate_relationship`. + + :param collection_class: the Python collection class that will be used + when a new :func:`_orm.relationship` + object is created that represents a + collection. Defaults to ``list``. + + :param schema: Schema name to reflect when reflecting tables using + the :paramref:`.AutomapBase.prepare.autoload_with` parameter. The name + is passed to the :paramref:`_schema.MetaData.reflect.schema` parameter + of :meth:`_schema.MetaData.reflect`. When omitted, the default schema + in use by the database connection is used. + + .. note:: The :paramref:`.AutomapBase.prepare.schema` + parameter supports reflection of a single schema at a time. + In order to include tables from many schemas, use + multiple calls to :meth:`.AutomapBase.prepare`. + + For an overview of multiple-schema automap including the use + of additional naming conventions to resolve table name + conflicts, see the section :ref:`automap_by_module`. + + .. versionadded:: 2.0 :meth:`.AutomapBase.prepare` supports being + directly invoked any number of times, keeping track of tables + that have already been processed to avoid processing them + a second time. + + :param reflection_options: When present, this dictionary of options + will be passed to :meth:`_schema.MetaData.reflect` + to supply general reflection-specific options like ``only`` and/or + dialect-specific options like ``oracle_resolve_synonyms``. + + .. versionadded:: 1.4 + + """ + + for mr in cls.__mro__: + if "_sa_automapbase_bookkeeping" in mr.__dict__: + automap_base = cast("Type[AutomapBase]", mr) + break + else: + assert False, "Can't locate automap base in class hierarchy" + + glbls = globals() + if classname_for_table is None: + classname_for_table = glbls["classname_for_table"] + if name_for_scalar_relationship is None: + name_for_scalar_relationship = glbls[ + "name_for_scalar_relationship" + ] + if name_for_collection_relationship is None: + name_for_collection_relationship = glbls[ + "name_for_collection_relationship" + ] + if generate_relationship is None: + generate_relationship = glbls["generate_relationship"] + if collection_class is None: + collection_class = list + + if autoload_with: + reflect = True + + if engine: + autoload_with = engine + + if reflect: + assert autoload_with + opts = dict( + schema=schema, + extend_existing=True, + autoload_replace=False, + ) + if reflection_options: + opts.update(reflection_options) + cls.metadata.reflect(autoload_with, **opts) # type: ignore[arg-type] # noqa: E501 + + with _CONFIGURE_MUTEX: + table_to_map_config: Union[ + Dict[Optional[Table], _DeferredMapperConfig], + Dict[Table, _DeferredMapperConfig], + ] = { + cast("Table", m.local_table): m + for m in _DeferredMapperConfig.classes_for_base( + cls, sort=False + ) + } + + many_to_many: List[ + Tuple[Table, Table, List[ForeignKeyConstraint], Table] + ] + many_to_many = [] + + bookkeeping = automap_base._sa_automapbase_bookkeeping + metadata_tables = cls.metadata.tables + + for table_key in set(metadata_tables).difference( + bookkeeping.table_keys + ): + table = metadata_tables[table_key] + bookkeeping.table_keys.add(table_key) + + lcl_m2m, rem_m2m, m2m_const = _is_many_to_many(cls, table) + if lcl_m2m is not None: + assert rem_m2m is not None + assert m2m_const is not None + many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table)) + elif not table.primary_key: + continue + elif table not in table_to_map_config: + clsdict: Dict[str, Any] = {"__table__": table} + if modulename_for_table is not None: + new_module = modulename_for_table( + cls, table.name, table + ) + if new_module is not None: + clsdict["__module__"] = new_module + else: + new_module = None + + newname = classname_for_table(cls, table.name, table) + if new_module is None and newname in cls.classes: + util.warn( + "Ignoring duplicate class name " + f"'{newname}' " + "received in automap base for table " + f"{table.key} without " + "``__module__`` being set; consider using the " + "``modulename_for_table`` hook" + ) + continue + + mapped_cls = type( + newname, + (automap_base,), + clsdict, + ) + map_config = _DeferredMapperConfig.config_for_cls( + mapped_cls + ) + assert map_config.cls.__name__ == newname + if new_module is None: + cls.classes[newname] = mapped_cls + + by_module_properties: ByModuleProperties = cls.by_module + for token in map_config.cls.__module__.split("."): + if token not in by_module_properties: + by_module_properties[token] = util.Properties({}) + + props = by_module_properties[token] + + # we can assert this because the clsregistry + # module would have raised if there was a mismatch + # between modules/classes already. + # see test_cls_schema_name_conflict + assert isinstance(props, Properties) + by_module_properties = props + + by_module_properties[map_config.cls.__name__] = mapped_cls + + table_to_map_config[table] = map_config + + for map_config in table_to_map_config.values(): + _relationships_for_fks( + automap_base, + map_config, + table_to_map_config, + collection_class, + name_for_scalar_relationship, + name_for_collection_relationship, + generate_relationship, + ) + + for lcl_m2m, rem_m2m, m2m_const, table in many_to_many: + _m2m_relationship( + automap_base, + lcl_m2m, + rem_m2m, + m2m_const, + table, + table_to_map_config, + collection_class, + name_for_scalar_relationship, + name_for_collection_relationship, + generate_relationship, + ) + + for map_config in _DeferredMapperConfig.classes_for_base( + automap_base + ): + map_config.map() + + _sa_decl_prepare = True + """Indicate that the mapping of classes should be deferred. + + The presence of this attribute name indicates to declarative + that the call to mapper() should not occur immediately; instead, + information about the table and attributes to be mapped are gathered + into an internal structure called _DeferredMapperConfig. These + objects can be collected later using classes_for_base(), additional + mapping decisions can be made, and then the map() method will actually + apply the mapping. + + The only real reason this deferral of the whole + thing is needed is to support primary key columns that aren't reflected + yet when the class is declared; everything else can theoretically be + added to the mapper later. However, the _DeferredMapperConfig is a + nice interface in any case which exists at that not usually exposed point + at which declarative has the class and the Table but hasn't called + mapper() yet. + + """ + + @classmethod + def _sa_raise_deferred_config(cls) -> NoReturn: + raise orm_exc.UnmappedClassError( + cls, + msg="Class %s is a subclass of AutomapBase. " + "Mappings are not produced until the .prepare() " + "method is called on the class hierarchy." + % orm_exc._safe_cls_name(cls), + ) + + +@dataclasses.dataclass +class _Bookkeeping: + __slots__ = ("table_keys",) + + table_keys: Set[str] + + +def automap_base( + declarative_base: Optional[Type[Any]] = None, **kw: Any +) -> Any: + r"""Produce a declarative automap base. + + This function produces a new base class that is a product of the + :class:`.AutomapBase` class as well a declarative base produced by + :func:`.declarative.declarative_base`. + + All parameters other than ``declarative_base`` are keyword arguments + that are passed directly to the :func:`.declarative.declarative_base` + function. + + :param declarative_base: an existing class produced by + :func:`.declarative.declarative_base`. When this is passed, the function + no longer invokes :func:`.declarative.declarative_base` itself, and all + other keyword arguments are ignored. + + :param \**kw: keyword arguments are passed along to + :func:`.declarative.declarative_base`. + + """ + if declarative_base is None: + Base = _declarative_base(**kw) + else: + Base = declarative_base + + return type( + Base.__name__, + (AutomapBase, Base), + { + "__abstract__": True, + "classes": util.Properties({}), + "by_module": util.Properties({}), + "_sa_automapbase_bookkeeping": _Bookkeeping(set()), + }, + ) + + +def _is_many_to_many( + automap_base: Type[Any], table: Table +) -> Tuple[ + Optional[Table], Optional[Table], Optional[list[ForeignKeyConstraint]] +]: + fk_constraints = [ + const + for const in table.constraints + if isinstance(const, ForeignKeyConstraint) + ] + if len(fk_constraints) != 2: + return None, None, None + + cols: List[Column[Any]] = sum( + [ + [fk.parent for fk in fk_constraint.elements] + for fk_constraint in fk_constraints + ], + [], + ) + + if set(cols) != set(table.c): + return None, None, None + + return ( + fk_constraints[0].elements[0].column.table, + fk_constraints[1].elements[0].column.table, + fk_constraints, + ) + + +def _relationships_for_fks( + automap_base: Type[Any], + map_config: _DeferredMapperConfig, + table_to_map_config: Union[ + Dict[Optional[Table], _DeferredMapperConfig], + Dict[Table, _DeferredMapperConfig], + ], + collection_class: type, + name_for_scalar_relationship: NameForScalarRelationshipType, + name_for_collection_relationship: NameForCollectionRelationshipType, + generate_relationship: GenerateRelationshipType, +) -> None: + local_table = cast("Optional[Table]", map_config.local_table) + local_cls = cast( + "Optional[Type[Any]]", map_config.cls + ) # derived from a weakref, may be None + + if local_table is None or local_cls is None: + return + for constraint in local_table.constraints: + if isinstance(constraint, ForeignKeyConstraint): + fks = constraint.elements + referred_table = fks[0].column.table + referred_cfg = table_to_map_config.get(referred_table, None) + if referred_cfg is None: + continue + referred_cls = referred_cfg.cls + + if local_cls is not referred_cls and issubclass( + local_cls, referred_cls + ): + continue + + relationship_name = name_for_scalar_relationship( + automap_base, local_cls, referred_cls, constraint + ) + backref_name = name_for_collection_relationship( + automap_base, referred_cls, local_cls, constraint + ) + + o2m_kws: Dict[str, Union[str, bool]] = {} + nullable = False not in {fk.parent.nullable for fk in fks} + if not nullable: + o2m_kws["cascade"] = "all, delete-orphan" + + if ( + constraint.ondelete + and constraint.ondelete.lower() == "cascade" + ): + o2m_kws["passive_deletes"] = True + else: + if ( + constraint.ondelete + and constraint.ondelete.lower() == "set null" + ): + o2m_kws["passive_deletes"] = True + + create_backref = backref_name not in referred_cfg.properties + + if relationship_name not in map_config.properties: + if create_backref: + backref_obj = generate_relationship( + automap_base, + interfaces.ONETOMANY, + backref, + backref_name, + referred_cls, + local_cls, + collection_class=collection_class, + **o2m_kws, + ) + else: + backref_obj = None + rel = generate_relationship( + automap_base, + interfaces.MANYTOONE, + relationship, + relationship_name, + local_cls, + referred_cls, + foreign_keys=[fk.parent for fk in constraint.elements], + backref=backref_obj, + remote_side=[fk.column for fk in constraint.elements], + ) + if rel is not None: + map_config.properties[relationship_name] = rel + if not create_backref: + referred_cfg.properties[ + backref_name + ].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501 + elif create_backref: + rel = generate_relationship( + automap_base, + interfaces.ONETOMANY, + relationship, + backref_name, + referred_cls, + local_cls, + foreign_keys=[fk.parent for fk in constraint.elements], + back_populates=relationship_name, + collection_class=collection_class, + **o2m_kws, + ) + if rel is not None: + referred_cfg.properties[backref_name] = rel + map_config.properties[ + relationship_name + ].back_populates = backref_name # type: ignore[union-attr] + + +def _m2m_relationship( + automap_base: Type[Any], + lcl_m2m: Table, + rem_m2m: Table, + m2m_const: List[ForeignKeyConstraint], + table: Table, + table_to_map_config: Union[ + Dict[Optional[Table], _DeferredMapperConfig], + Dict[Table, _DeferredMapperConfig], + ], + collection_class: type, + name_for_scalar_relationship: NameForCollectionRelationshipType, + name_for_collection_relationship: NameForCollectionRelationshipType, + generate_relationship: GenerateRelationshipType, +) -> None: + map_config = table_to_map_config.get(lcl_m2m, None) + referred_cfg = table_to_map_config.get(rem_m2m, None) + if map_config is None or referred_cfg is None: + return + + local_cls = map_config.cls + referred_cls = referred_cfg.cls + + relationship_name = name_for_collection_relationship( + automap_base, local_cls, referred_cls, m2m_const[0] + ) + backref_name = name_for_collection_relationship( + automap_base, referred_cls, local_cls, m2m_const[1] + ) + + create_backref = backref_name not in referred_cfg.properties + + if table in table_to_map_config: + overlaps = "__*" + else: + overlaps = None + + if relationship_name not in map_config.properties: + if create_backref: + backref_obj = generate_relationship( + automap_base, + interfaces.MANYTOMANY, + backref, + backref_name, + referred_cls, + local_cls, + collection_class=collection_class, + overlaps=overlaps, + ) + else: + backref_obj = None + + rel = generate_relationship( + automap_base, + interfaces.MANYTOMANY, + relationship, + relationship_name, + local_cls, + referred_cls, + overlaps=overlaps, + secondary=table, + primaryjoin=and_( + fk.column == fk.parent for fk in m2m_const[0].elements + ), # type: ignore [arg-type] + secondaryjoin=and_( + fk.column == fk.parent for fk in m2m_const[1].elements + ), # type: ignore [arg-type] + backref=backref_obj, + collection_class=collection_class, + ) + if rel is not None: + map_config.properties[relationship_name] = rel + + if not create_backref: + referred_cfg.properties[ + backref_name + ].back_populates = relationship_name # type: ignore[union-attr] # noqa: E501 + elif create_backref: + rel = generate_relationship( + automap_base, + interfaces.MANYTOMANY, + relationship, + backref_name, + referred_cls, + local_cls, + overlaps=overlaps, + secondary=table, + primaryjoin=and_( + fk.column == fk.parent for fk in m2m_const[1].elements + ), # type: ignore [arg-type] + secondaryjoin=and_( + fk.column == fk.parent for fk in m2m_const[0].elements + ), # type: ignore [arg-type] + back_populates=relationship_name, + collection_class=collection_class, + ) + if rel is not None: + referred_cfg.properties[backref_name] = rel + map_config.properties[ + relationship_name + ].back_populates = backref_name # type: ignore[union-attr] diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/baked.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/baked.py new file mode 100644 index 0000000000000000000000000000000000000000..1475d0bfd9a7e73eca257493277e700943772e88 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/baked.py @@ -0,0 +1,570 @@ +# ext/baked.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + + +"""Baked query extension. + +Provides a creational pattern for the :class:`.query.Query` object which +allows the fully constructed object, Core select statement, and string +compiled result to be fully cached. + + +""" + +import collections.abc as collections_abc +import logging + +from .. import exc as sa_exc +from .. import util +from ..orm import exc as orm_exc +from ..orm.query import Query +from ..orm.session import Session +from ..sql import func +from ..sql import literal_column +from ..sql import util as sql_util + + +log = logging.getLogger(__name__) + + +class Bakery: + """Callable which returns a :class:`.BakedQuery`. + + This object is returned by the class method + :meth:`.BakedQuery.bakery`. It exists as an object + so that the "cache" can be easily inspected. + + .. versionadded:: 1.2 + + + """ + + __slots__ = "cls", "cache" + + def __init__(self, cls_, cache): + self.cls = cls_ + self.cache = cache + + def __call__(self, initial_fn, *args): + return self.cls(self.cache, initial_fn, args) + + +class BakedQuery: + """A builder object for :class:`.query.Query` objects.""" + + __slots__ = "steps", "_bakery", "_cache_key", "_spoiled" + + def __init__(self, bakery, initial_fn, args=()): + self._cache_key = () + self._update_cache_key(initial_fn, args) + self.steps = [initial_fn] + self._spoiled = False + self._bakery = bakery + + @classmethod + def bakery(cls, size=200, _size_alert=None): + """Construct a new bakery. + + :return: an instance of :class:`.Bakery` + + """ + + return Bakery(cls, util.LRUCache(size, size_alert=_size_alert)) + + def _clone(self): + b1 = BakedQuery.__new__(BakedQuery) + b1._cache_key = self._cache_key + b1.steps = list(self.steps) + b1._bakery = self._bakery + b1._spoiled = self._spoiled + return b1 + + def _update_cache_key(self, fn, args=()): + self._cache_key += (fn.__code__,) + args + + def __iadd__(self, other): + if isinstance(other, tuple): + self.add_criteria(*other) + else: + self.add_criteria(other) + return self + + def __add__(self, other): + if isinstance(other, tuple): + return self.with_criteria(*other) + else: + return self.with_criteria(other) + + def add_criteria(self, fn, *args): + """Add a criteria function to this :class:`.BakedQuery`. + + This is equivalent to using the ``+=`` operator to + modify a :class:`.BakedQuery` in-place. + + """ + self._update_cache_key(fn, args) + self.steps.append(fn) + return self + + def with_criteria(self, fn, *args): + """Add a criteria function to a :class:`.BakedQuery` cloned from this + one. + + This is equivalent to using the ``+`` operator to + produce a new :class:`.BakedQuery` with modifications. + + """ + return self._clone().add_criteria(fn, *args) + + def for_session(self, session): + """Return a :class:`_baked.Result` object for this + :class:`.BakedQuery`. + + This is equivalent to calling the :class:`.BakedQuery` as a + Python callable, e.g. ``result = my_baked_query(session)``. + + """ + return Result(self, session) + + def __call__(self, session): + return self.for_session(session) + + def spoil(self, full=False): + """Cancel any query caching that will occur on this BakedQuery object. + + The BakedQuery can continue to be used normally, however additional + creational functions will not be cached; they will be called + on every invocation. + + This is to support the case where a particular step in constructing + a baked query disqualifies the query from being cacheable, such + as a variant that relies upon some uncacheable value. + + :param full: if False, only functions added to this + :class:`.BakedQuery` object subsequent to the spoil step will be + non-cached; the state of the :class:`.BakedQuery` up until + this point will be pulled from the cache. If True, then the + entire :class:`_query.Query` object is built from scratch each + time, with all creational functions being called on each + invocation. + + """ + if not full and not self._spoiled: + _spoil_point = self._clone() + _spoil_point._cache_key += ("_query_only",) + self.steps = [_spoil_point._retrieve_baked_query] + self._spoiled = True + return self + + def _effective_key(self, session): + """Return the key that actually goes into the cache dictionary for + this :class:`.BakedQuery`, taking into account the given + :class:`.Session`. + + This basically means we also will include the session's query_class, + as the actual :class:`_query.Query` object is part of what's cached + and needs to match the type of :class:`_query.Query` that a later + session will want to use. + + """ + return self._cache_key + (session._query_cls,) + + def _with_lazyload_options(self, options, effective_path, cache_path=None): + """Cloning version of _add_lazyload_options.""" + q = self._clone() + q._add_lazyload_options(options, effective_path, cache_path=cache_path) + return q + + def _add_lazyload_options(self, options, effective_path, cache_path=None): + """Used by per-state lazy loaders to add options to the + "lazy load" query from a parent query. + + Creates a cache key based on given load path and query options; + if a repeatable cache key cannot be generated, the query is + "spoiled" so that it won't use caching. + + """ + + key = () + + if not cache_path: + cache_path = effective_path + + for opt in options: + if opt._is_legacy_option or opt._is_compile_state: + ck = opt._generate_cache_key() + if ck is None: + self.spoil(full=True) + else: + assert not ck[1], ( + "loader options with variable bound parameters " + "not supported with baked queries. Please " + "use new-style select() statements for cached " + "ORM queries." + ) + key += ck[0] + + self.add_criteria( + lambda q: q._with_current_path(effective_path).options(*options), + cache_path.path, + key, + ) + + def _retrieve_baked_query(self, session): + query = self._bakery.get(self._effective_key(session), None) + if query is None: + query = self._as_query(session) + self._bakery[self._effective_key(session)] = query.with_session( + None + ) + return query.with_session(session) + + def _bake(self, session): + query = self._as_query(session) + query.session = None + + # in 1.4, this is where before_compile() event is + # invoked + statement = query._statement_20() + + # if the query is not safe to cache, we still do everything as though + # we did cache it, since the receiver of _bake() assumes subqueryload + # context was set up, etc. + # + # note also we want to cache the statement itself because this + # allows the statement itself to hold onto its cache key that is + # used by the Connection, which in itself is more expensive to + # generate than what BakedQuery was able to provide in 1.3 and prior + + if statement._compile_options._bake_ok: + self._bakery[self._effective_key(session)] = ( + query, + statement, + ) + + return query, statement + + def to_query(self, query_or_session): + """Return the :class:`_query.Query` object for use as a subquery. + + This method should be used within the lambda callable being used + to generate a step of an enclosing :class:`.BakedQuery`. The + parameter should normally be the :class:`_query.Query` object that + is passed to the lambda:: + + sub_bq = self.bakery(lambda s: s.query(User.name)) + sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address) + + main_bq = self.bakery(lambda s: s.query(Address)) + main_bq += lambda q: q.filter(sub_bq.to_query(q).exists()) + + In the case where the subquery is used in the first callable against + a :class:`.Session`, the :class:`.Session` is also accepted:: + + sub_bq = self.bakery(lambda s: s.query(User.name)) + sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address) + + main_bq = self.bakery( + lambda s: s.query(Address.id, sub_bq.to_query(q).scalar_subquery()) + ) + + :param query_or_session: a :class:`_query.Query` object or a class + :class:`.Session` object, that is assumed to be within the context + of an enclosing :class:`.BakedQuery` callable. + + + .. versionadded:: 1.3 + + + """ # noqa: E501 + + if isinstance(query_or_session, Session): + session = query_or_session + elif isinstance(query_or_session, Query): + session = query_or_session.session + if session is None: + raise sa_exc.ArgumentError( + "Given Query needs to be associated with a Session" + ) + else: + raise TypeError( + "Query or Session object expected, got %r." + % type(query_or_session) + ) + return self._as_query(session) + + def _as_query(self, session): + query = self.steps[0](session) + + for step in self.steps[1:]: + query = step(query) + + return query + + +class Result: + """Invokes a :class:`.BakedQuery` against a :class:`.Session`. + + The :class:`_baked.Result` object is where the actual :class:`.query.Query` + object gets created, or retrieved from the cache, + against a target :class:`.Session`, and is then invoked for results. + + """ + + __slots__ = "bq", "session", "_params", "_post_criteria" + + def __init__(self, bq, session): + self.bq = bq + self.session = session + self._params = {} + self._post_criteria = [] + + def params(self, *args, **kw): + """Specify parameters to be replaced into the string SQL statement.""" + + if len(args) == 1: + kw.update(args[0]) + elif len(args) > 0: + raise sa_exc.ArgumentError( + "params() takes zero or one positional argument, " + "which is a dictionary." + ) + self._params.update(kw) + return self + + def _using_post_criteria(self, fns): + if fns: + self._post_criteria.extend(fns) + return self + + def with_post_criteria(self, fn): + """Add a criteria function that will be applied post-cache. + + This adds a function that will be run against the + :class:`_query.Query` object after it is retrieved from the + cache. This currently includes **only** the + :meth:`_query.Query.params` and :meth:`_query.Query.execution_options` + methods. + + .. warning:: :meth:`_baked.Result.with_post_criteria` + functions are applied + to the :class:`_query.Query` + object **after** the query's SQL statement + object has been retrieved from the cache. Only + :meth:`_query.Query.params` and + :meth:`_query.Query.execution_options` + methods should be used. + + + .. versionadded:: 1.2 + + + """ + return self._using_post_criteria([fn]) + + def _as_query(self): + q = self.bq._as_query(self.session).params(self._params) + for fn in self._post_criteria: + q = fn(q) + return q + + def __str__(self): + return str(self._as_query()) + + def __iter__(self): + return self._iter().__iter__() + + def _iter(self): + bq = self.bq + + if not self.session.enable_baked_queries or bq._spoiled: + return self._as_query()._iter() + + query, statement = bq._bakery.get( + bq._effective_key(self.session), (None, None) + ) + if query is None: + query, statement = bq._bake(self.session) + + if self._params: + q = query.params(self._params) + else: + q = query + for fn in self._post_criteria: + q = fn(q) + + params = q._params + execution_options = dict(q._execution_options) + execution_options.update( + { + "_sa_orm_load_options": q.load_options, + "compiled_cache": bq._bakery, + } + ) + + result = self.session.execute( + statement, params, execution_options=execution_options + ) + if result._attributes.get("is_single_entity", False): + result = result.scalars() + + if result._attributes.get("filtered", False): + result = result.unique() + + return result + + def count(self): + """return the 'count'. + + Equivalent to :meth:`_query.Query.count`. + + Note this uses a subquery to ensure an accurate count regardless + of the structure of the original statement. + + """ + + col = func.count(literal_column("*")) + bq = self.bq.with_criteria(lambda q: q._legacy_from_self(col)) + return bq.for_session(self.session).params(self._params).scalar() + + def scalar(self): + """Return the first element of the first result or None + if no rows present. If multiple rows are returned, + raises MultipleResultsFound. + + Equivalent to :meth:`_query.Query.scalar`. + + """ + try: + ret = self.one() + if not isinstance(ret, collections_abc.Sequence): + return ret + return ret[0] + except orm_exc.NoResultFound: + return None + + def first(self): + """Return the first row. + + Equivalent to :meth:`_query.Query.first`. + + """ + + bq = self.bq.with_criteria(lambda q: q.slice(0, 1)) + return ( + bq.for_session(self.session) + .params(self._params) + ._using_post_criteria(self._post_criteria) + ._iter() + .first() + ) + + def one(self): + """Return exactly one result or raise an exception. + + Equivalent to :meth:`_query.Query.one`. + + """ + return self._iter().one() + + def one_or_none(self): + """Return one or zero results, or raise an exception for multiple + rows. + + Equivalent to :meth:`_query.Query.one_or_none`. + + """ + return self._iter().one_or_none() + + def all(self): + """Return all rows. + + Equivalent to :meth:`_query.Query.all`. + + """ + return self._iter().all() + + def get(self, ident): + """Retrieve an object based on identity. + + Equivalent to :meth:`_query.Query.get`. + + """ + + query = self.bq.steps[0](self.session) + return query._get_impl(ident, self._load_on_pk_identity) + + def _load_on_pk_identity(self, session, query, primary_key_identity, **kw): + """Load the given primary key identity from the database.""" + + mapper = query._raw_columns[0]._annotations["parententity"] + + _get_clause, _get_params = mapper._get_clause + + def setup(query): + _lcl_get_clause = _get_clause + q = query._clone() + q._get_condition() + q._order_by = None + + # None present in ident - turn those comparisons + # into "IS NULL" + if None in primary_key_identity: + nones = { + _get_params[col].key + for col, value in zip( + mapper.primary_key, primary_key_identity + ) + if value is None + } + _lcl_get_clause = sql_util.adapt_criterion_to_null( + _lcl_get_clause, nones + ) + + # TODO: can mapper._get_clause be pre-adapted? + q._where_criteria = ( + sql_util._deep_annotate(_lcl_get_clause, {"_orm_adapt": True}), + ) + + for fn in self._post_criteria: + q = fn(q) + return q + + # cache the query against a key that includes + # which positions in the primary key are NULL + # (remember, we can map to an OUTER JOIN) + bq = self.bq + + # add the clause we got from mapper._get_clause to the cache + # key so that if a race causes multiple calls to _get_clause, + # we've cached on ours + bq = bq._clone() + bq._cache_key += (_get_clause,) + + bq = bq.with_criteria( + setup, tuple(elem is None for elem in primary_key_identity) + ) + + params = { + _get_params[primary_key].key: id_val + for id_val, primary_key in zip( + primary_key_identity, mapper.primary_key + ) + } + + result = list(bq.for_session(self.session).params(**params)) + l = len(result) + if l > 1: + raise orm_exc.MultipleResultsFound() + elif l: + return result[0] + else: + return None + + +bakery = BakedQuery.bakery diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/compiler.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..51430dadfe58354ca703d9a96e5a37c66679f790 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/compiler.py @@ -0,0 +1,600 @@ +# ext/compiler.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +r"""Provides an API for creation of custom ClauseElements and compilers. + +Synopsis +======== + +Usage involves the creation of one or more +:class:`~sqlalchemy.sql.expression.ClauseElement` subclasses and one or +more callables defining its compilation:: + + from sqlalchemy.ext.compiler import compiles + from sqlalchemy.sql.expression import ColumnClause + + + class MyColumn(ColumnClause): + inherit_cache = True + + + @compiles(MyColumn) + def compile_mycolumn(element, compiler, **kw): + return "[%s]" % element.name + +Above, ``MyColumn`` extends :class:`~sqlalchemy.sql.expression.ColumnClause`, +the base expression element for named column objects. The ``compiles`` +decorator registers itself with the ``MyColumn`` class so that it is invoked +when the object is compiled to a string:: + + from sqlalchemy import select + + s = select(MyColumn("x"), MyColumn("y")) + print(str(s)) + +Produces: + +.. sourcecode:: sql + + SELECT [x], [y] + +Dialect-specific compilation rules +================================== + +Compilers can also be made dialect-specific. The appropriate compiler will be +invoked for the dialect in use:: + + from sqlalchemy.schema import DDLElement + + + class AlterColumn(DDLElement): + inherit_cache = False + + def __init__(self, column, cmd): + self.column = column + self.cmd = cmd + + + @compiles(AlterColumn) + def visit_alter_column(element, compiler, **kw): + return "ALTER COLUMN %s ..." % element.column.name + + + @compiles(AlterColumn, "postgresql") + def visit_alter_column(element, compiler, **kw): + return "ALTER TABLE %s ALTER COLUMN %s ..." % ( + element.table.name, + element.column.name, + ) + +The second ``visit_alter_table`` will be invoked when any ``postgresql`` +dialect is used. + +.. _compilerext_compiling_subelements: + +Compiling sub-elements of a custom expression construct +======================================================= + +The ``compiler`` argument is the +:class:`~sqlalchemy.engine.interfaces.Compiled` object in use. This object +can be inspected for any information about the in-progress compilation, +including ``compiler.dialect``, ``compiler.statement`` etc. The +:class:`~sqlalchemy.sql.compiler.SQLCompiler` and +:class:`~sqlalchemy.sql.compiler.DDLCompiler` both include a ``process()`` +method which can be used for compilation of embedded attributes:: + + from sqlalchemy.sql.expression import Executable, ClauseElement + + + class InsertFromSelect(Executable, ClauseElement): + inherit_cache = False + + def __init__(self, table, select): + self.table = table + self.select = select + + + @compiles(InsertFromSelect) + def visit_insert_from_select(element, compiler, **kw): + return "INSERT INTO %s (%s)" % ( + compiler.process(element.table, asfrom=True, **kw), + compiler.process(element.select, **kw), + ) + + + insert = InsertFromSelect(t1, select(t1).where(t1.c.x > 5)) + print(insert) + +Produces (formatted for readability): + +.. sourcecode:: sql + + INSERT INTO mytable ( + SELECT mytable.x, mytable.y, mytable.z + FROM mytable + WHERE mytable.x > :x_1 + ) + +.. note:: + + The above ``InsertFromSelect`` construct is only an example, this actual + functionality is already available using the + :meth:`_expression.Insert.from_select` method. + + +Cross Compiling between SQL and DDL compilers +--------------------------------------------- + +SQL and DDL constructs are each compiled using different base compilers - +``SQLCompiler`` and ``DDLCompiler``. A common need is to access the +compilation rules of SQL expressions from within a DDL expression. The +``DDLCompiler`` includes an accessor ``sql_compiler`` for this reason, such as +below where we generate a CHECK constraint that embeds a SQL expression:: + + @compiles(MyConstraint) + def compile_my_constraint(constraint, ddlcompiler, **kw): + kw["literal_binds"] = True + return "CONSTRAINT %s CHECK (%s)" % ( + constraint.name, + ddlcompiler.sql_compiler.process(constraint.expression, **kw), + ) + +Above, we add an additional flag to the process step as called by +:meth:`.SQLCompiler.process`, which is the ``literal_binds`` flag. This +indicates that any SQL expression which refers to a :class:`.BindParameter` +object or other "literal" object such as those which refer to strings or +integers should be rendered **in-place**, rather than being referred to as +a bound parameter; when emitting DDL, bound parameters are typically not +supported. + + +Changing the default compilation of existing constructs +======================================================= + +The compiler extension applies just as well to the existing constructs. When +overriding the compilation of a built in SQL construct, the @compiles +decorator is invoked upon the appropriate class (be sure to use the class, +i.e. ``Insert`` or ``Select``, instead of the creation function such +as ``insert()`` or ``select()``). + +Within the new compilation function, to get at the "original" compilation +routine, use the appropriate visit_XXX method - this +because compiler.process() will call upon the overriding routine and cause +an endless loop. Such as, to add "prefix" to all insert statements:: + + from sqlalchemy.sql.expression import Insert + + + @compiles(Insert) + def prefix_inserts(insert, compiler, **kw): + return compiler.visit_insert(insert.prefix_with("some prefix"), **kw) + +The above compiler will prefix all INSERT statements with "some prefix" when +compiled. + +.. _type_compilation_extension: + +Changing Compilation of Types +============================= + +``compiler`` works for types, too, such as below where we implement the +MS-SQL specific 'max' keyword for ``String``/``VARCHAR``:: + + @compiles(String, "mssql") + @compiles(VARCHAR, "mssql") + def compile_varchar(element, compiler, **kw): + if element.length == "max": + return "VARCHAR('max')" + else: + return compiler.visit_VARCHAR(element, **kw) + + + foo = Table("foo", metadata, Column("data", VARCHAR("max"))) + +Subclassing Guidelines +====================== + +A big part of using the compiler extension is subclassing SQLAlchemy +expression constructs. To make this easier, the expression and +schema packages feature a set of "bases" intended for common tasks. +A synopsis is as follows: + +* :class:`~sqlalchemy.sql.expression.ClauseElement` - This is the root + expression class. Any SQL expression can be derived from this base, and is + probably the best choice for longer constructs such as specialized INSERT + statements. + +* :class:`~sqlalchemy.sql.expression.ColumnElement` - The root of all + "column-like" elements. Anything that you'd place in the "columns" clause of + a SELECT statement (as well as order by and group by) can derive from this - + the object will automatically have Python "comparison" behavior. + + :class:`~sqlalchemy.sql.expression.ColumnElement` classes want to have a + ``type`` member which is expression's return type. This can be established + at the instance level in the constructor, or at the class level if its + generally constant:: + + class timestamp(ColumnElement): + type = TIMESTAMP() + inherit_cache = True + +* :class:`~sqlalchemy.sql.functions.FunctionElement` - This is a hybrid of a + ``ColumnElement`` and a "from clause" like object, and represents a SQL + function or stored procedure type of call. Since most databases support + statements along the line of "SELECT FROM " + ``FunctionElement`` adds in the ability to be used in the FROM clause of a + ``select()`` construct:: + + from sqlalchemy.sql.expression import FunctionElement + + + class coalesce(FunctionElement): + name = "coalesce" + inherit_cache = True + + + @compiles(coalesce) + def compile(element, compiler, **kw): + return "coalesce(%s)" % compiler.process(element.clauses, **kw) + + + @compiles(coalesce, "oracle") + def compile(element, compiler, **kw): + if len(element.clauses) > 2: + raise TypeError( + "coalesce only supports two arguments on " "Oracle Database" + ) + return "nvl(%s)" % compiler.process(element.clauses, **kw) + +* :class:`.ExecutableDDLElement` - The root of all DDL expressions, + like CREATE TABLE, ALTER TABLE, etc. Compilation of + :class:`.ExecutableDDLElement` subclasses is issued by a + :class:`.DDLCompiler` instead of a :class:`.SQLCompiler`. + :class:`.ExecutableDDLElement` can also be used as an event hook in + conjunction with event hooks like :meth:`.DDLEvents.before_create` and + :meth:`.DDLEvents.after_create`, allowing the construct to be invoked + automatically during CREATE TABLE and DROP TABLE sequences. + + .. seealso:: + + :ref:`metadata_ddl_toplevel` - contains examples of associating + :class:`.DDL` objects (which are themselves :class:`.ExecutableDDLElement` + instances) with :class:`.DDLEvents` event hooks. + +* :class:`~sqlalchemy.sql.expression.Executable` - This is a mixin which + should be used with any expression class that represents a "standalone" + SQL statement that can be passed directly to an ``execute()`` method. It + is already implicit within ``DDLElement`` and ``FunctionElement``. + +Most of the above constructs also respond to SQL statement caching. A +subclassed construct will want to define the caching behavior for the object, +which usually means setting the flag ``inherit_cache`` to the value of +``False`` or ``True``. See the next section :ref:`compilerext_caching` +for background. + + +.. _compilerext_caching: + +Enabling Caching Support for Custom Constructs +============================================== + +SQLAlchemy as of version 1.4 includes a +:ref:`SQL compilation caching facility ` which will allow +equivalent SQL constructs to cache their stringified form, along with other +structural information used to fetch results from the statement. + +For reasons discussed at :ref:`caching_caveats`, the implementation of this +caching system takes a conservative approach towards including custom SQL +constructs and/or subclasses within the caching system. This includes that +any user-defined SQL constructs, including all the examples for this +extension, will not participate in caching by default unless they positively +assert that they are able to do so. The :attr:`.HasCacheKey.inherit_cache` +attribute when set to ``True`` at the class level of a specific subclass +will indicate that instances of this class may be safely cached, using the +cache key generation scheme of the immediate superclass. This applies +for example to the "synopsis" example indicated previously:: + + class MyColumn(ColumnClause): + inherit_cache = True + + + @compiles(MyColumn) + def compile_mycolumn(element, compiler, **kw): + return "[%s]" % element.name + +Above, the ``MyColumn`` class does not include any new state that +affects its SQL compilation; the cache key of ``MyColumn`` instances will +make use of that of the ``ColumnClause`` superclass, meaning it will take +into account the class of the object (``MyColumn``), the string name and +datatype of the object:: + + >>> MyColumn("some_name", String())._generate_cache_key() + CacheKey( + key=('0', , + 'name', 'some_name', + 'type', (, + ('length', None), ('collation', None)) + ), bindparams=[]) + +For objects that are likely to be **used liberally as components within many +larger statements**, such as :class:`_schema.Column` subclasses and custom SQL +datatypes, it's important that **caching be enabled as much as possible**, as +this may otherwise negatively affect performance. + +An example of an object that **does** contain state which affects its SQL +compilation is the one illustrated at :ref:`compilerext_compiling_subelements`; +this is an "INSERT FROM SELECT" construct that combines together a +:class:`_schema.Table` as well as a :class:`_sql.Select` construct, each of +which independently affect the SQL string generation of the construct. For +this class, the example illustrates that it simply does not participate in +caching:: + + class InsertFromSelect(Executable, ClauseElement): + inherit_cache = False + + def __init__(self, table, select): + self.table = table + self.select = select + + + @compiles(InsertFromSelect) + def visit_insert_from_select(element, compiler, **kw): + return "INSERT INTO %s (%s)" % ( + compiler.process(element.table, asfrom=True, **kw), + compiler.process(element.select, **kw), + ) + +While it is also possible that the above ``InsertFromSelect`` could be made to +produce a cache key that is composed of that of the :class:`_schema.Table` and +:class:`_sql.Select` components together, the API for this is not at the moment +fully public. However, for an "INSERT FROM SELECT" construct, which is only +used by itself for specific operations, caching is not as critical as in the +previous example. + +For objects that are **used in relative isolation and are generally +standalone**, such as custom :term:`DML` constructs like an "INSERT FROM +SELECT", **caching is generally less critical** as the lack of caching for such +a construct will have only localized implications for that specific operation. + + +Further Examples +================ + +"UTC timestamp" function +------------------------- + +A function that works like "CURRENT_TIMESTAMP" except applies the +appropriate conversions so that the time is in UTC time. Timestamps are best +stored in relational databases as UTC, without time zones. UTC so that your +database doesn't think time has gone backwards in the hour when daylight +savings ends, without timezones because timezones are like character +encodings - they're best applied only at the endpoints of an application +(i.e. convert to UTC upon user input, re-apply desired timezone upon display). + +For PostgreSQL and Microsoft SQL Server:: + + from sqlalchemy.sql import expression + from sqlalchemy.ext.compiler import compiles + from sqlalchemy.types import DateTime + + + class utcnow(expression.FunctionElement): + type = DateTime() + inherit_cache = True + + + @compiles(utcnow, "postgresql") + def pg_utcnow(element, compiler, **kw): + return "TIMEZONE('utc', CURRENT_TIMESTAMP)" + + + @compiles(utcnow, "mssql") + def ms_utcnow(element, compiler, **kw): + return "GETUTCDATE()" + +Example usage:: + + from sqlalchemy import Table, Column, Integer, String, DateTime, MetaData + + metadata = MetaData() + event = Table( + "event", + metadata, + Column("id", Integer, primary_key=True), + Column("description", String(50), nullable=False), + Column("timestamp", DateTime, server_default=utcnow()), + ) + +"GREATEST" function +------------------- + +The "GREATEST" function is given any number of arguments and returns the one +that is of the highest value - its equivalent to Python's ``max`` +function. A SQL standard version versus a CASE based version which only +accommodates two arguments:: + + from sqlalchemy.sql import expression, case + from sqlalchemy.ext.compiler import compiles + from sqlalchemy.types import Numeric + + + class greatest(expression.FunctionElement): + type = Numeric() + name = "greatest" + inherit_cache = True + + + @compiles(greatest) + def default_greatest(element, compiler, **kw): + return compiler.visit_function(element) + + + @compiles(greatest, "sqlite") + @compiles(greatest, "mssql") + @compiles(greatest, "oracle") + def case_greatest(element, compiler, **kw): + arg1, arg2 = list(element.clauses) + return compiler.process(case((arg1 > arg2, arg1), else_=arg2), **kw) + +Example usage:: + + Session.query(Account).filter( + greatest(Account.checking_balance, Account.savings_balance) > 10000 + ) + +"false" expression +------------------ + +Render a "false" constant expression, rendering as "0" on platforms that +don't have a "false" constant:: + + from sqlalchemy.sql import expression + from sqlalchemy.ext.compiler import compiles + + + class sql_false(expression.ColumnElement): + inherit_cache = True + + + @compiles(sql_false) + def default_false(element, compiler, **kw): + return "false" + + + @compiles(sql_false, "mssql") + @compiles(sql_false, "mysql") + @compiles(sql_false, "oracle") + def int_false(element, compiler, **kw): + return "0" + +Example usage:: + + from sqlalchemy import select, union_all + + exp = union_all( + select(users.c.name, sql_false().label("enrolled")), + select(customers.c.name, customers.c.enrolled), + ) + +""" +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Dict +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar + +from .. import exc +from ..sql import sqltypes + +if TYPE_CHECKING: + from ..sql.compiler import SQLCompiler + +_F = TypeVar("_F", bound=Callable[..., Any]) + + +def compiles(class_: Type[Any], *specs: str) -> Callable[[_F], _F]: + """Register a function as a compiler for a + given :class:`_expression.ClauseElement` type.""" + + def decorate(fn: _F) -> _F: + # get an existing @compiles handler + existing = class_.__dict__.get("_compiler_dispatcher", None) + + # get the original handler. All ClauseElement classes have one + # of these, but some TypeEngine classes will not. + existing_dispatch = getattr(class_, "_compiler_dispatch", None) + + if not existing: + existing = _dispatcher() + + if existing_dispatch: + + def _wrap_existing_dispatch( + element: Any, compiler: SQLCompiler, **kw: Any + ) -> Any: + try: + return existing_dispatch(element, compiler, **kw) + except exc.UnsupportedCompilationError as uce: + raise exc.UnsupportedCompilationError( + compiler, + type(element), + message="%s construct has no default " + "compilation handler." % type(element), + ) from uce + + existing.specs["default"] = _wrap_existing_dispatch + + # TODO: why is the lambda needed ? + setattr( + class_, + "_compiler_dispatch", + lambda *arg, **kw: existing(*arg, **kw), + ) + setattr(class_, "_compiler_dispatcher", existing) + + if specs: + for s in specs: + existing.specs[s] = fn + + else: + existing.specs["default"] = fn + return fn + + return decorate + + +def deregister(class_: Type[Any]) -> None: + """Remove all custom compilers associated with a given + :class:`_expression.ClauseElement` type. + + """ + + if hasattr(class_, "_compiler_dispatcher"): + class_._compiler_dispatch = class_._original_compiler_dispatch + del class_._compiler_dispatcher + + +class _dispatcher: + def __init__(self) -> None: + self.specs: Dict[str, Callable[..., Any]] = {} + + def __call__(self, element: Any, compiler: SQLCompiler, **kw: Any) -> Any: + # TODO: yes, this could also switch off of DBAPI in use. + fn = self.specs.get(compiler.dialect.name, None) + if not fn: + try: + fn = self.specs["default"] + except KeyError as ke: + raise exc.UnsupportedCompilationError( + compiler, + type(element), + message="%s construct has no default " + "compilation handler." % type(element), + ) from ke + + # if compilation includes add_to_result_map, collect add_to_result_map + # arguments from the user-defined callable, which are probably none + # because this is not public API. if it wasn't called, then call it + # ourselves. + arm = kw.get("add_to_result_map", None) + if arm: + arm_collection = [] + kw["add_to_result_map"] = lambda *args: arm_collection.append(args) + + expr = fn(element, compiler, **kw) + + if arm: + if not arm_collection: + arm_collection.append( + (None, None, (element,), sqltypes.NULLTYPE) + ) + for tup in arm_collection: + arm(*tup) + return expr diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/horizontal_shard.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/horizontal_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..9ee9e2b12e370d34fe66c9bae72bb24651c1f879 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/horizontal_shard.py @@ -0,0 +1,478 @@ +# ext/horizontal_shard.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Horizontal sharding support. + +Defines a rudimental 'horizontal sharding' system which allows a Session to +distribute queries and persistence operations across multiple databases. + +For a usage example, see the :ref:`examples_sharding` example included in +the source distribution. + +.. deepalchemy:: The horizontal sharding extension is an advanced feature, + involving a complex statement -> database interaction as well as + use of semi-public APIs for non-trivial cases. Simpler approaches to + referring to multiple database "shards", most commonly using a distinct + :class:`_orm.Session` per "shard", should always be considered first + before using this more complex and less-production-tested system. + + + +""" +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .. import event +from .. import exc +from .. import inspect +from .. import util +from ..orm import PassiveFlag +from ..orm._typing import OrmExecuteOptionsParameter +from ..orm.interfaces import ORMOption +from ..orm.mapper import Mapper +from ..orm.query import Query +from ..orm.session import _BindArguments +from ..orm.session import _PKIdentityArgument +from ..orm.session import Session +from ..util.typing import Protocol +from ..util.typing import Self + +if TYPE_CHECKING: + from ..engine.base import Connection + from ..engine.base import Engine + from ..engine.base import OptionEngine + from ..engine.result import IteratorResult + from ..engine.result import Result + from ..orm import LoaderCallableStatus + from ..orm._typing import _O + from ..orm.bulk_persistence import BulkUDCompileState + from ..orm.context import QueryContext + from ..orm.session import _EntityBindKey + from ..orm.session import _SessionBind + from ..orm.session import ORMExecuteState + from ..orm.state import InstanceState + from ..sql import Executable + from ..sql._typing import _TP + from ..sql.elements import ClauseElement + +__all__ = ["ShardedSession", "ShardedQuery"] + +_T = TypeVar("_T", bound=Any) + + +ShardIdentifier = str + + +class ShardChooser(Protocol): + def __call__( + self, + mapper: Optional[Mapper[_T]], + instance: Any, + clause: Optional[ClauseElement], + ) -> Any: ... + + +class IdentityChooser(Protocol): + def __call__( + self, + mapper: Mapper[_T], + primary_key: _PKIdentityArgument, + *, + lazy_loaded_from: Optional[InstanceState[Any]], + execution_options: OrmExecuteOptionsParameter, + bind_arguments: _BindArguments, + **kw: Any, + ) -> Any: ... + + +class ShardedQuery(Query[_T]): + """Query class used with :class:`.ShardedSession`. + + .. legacy:: The :class:`.ShardedQuery` is a subclass of the legacy + :class:`.Query` class. The :class:`.ShardedSession` now supports + 2.0 style execution via the :meth:`.ShardedSession.execute` method. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + assert isinstance(self.session, ShardedSession) + + self.identity_chooser = self.session.identity_chooser + self.execute_chooser = self.session.execute_chooser + self._shard_id = None + + def set_shard(self, shard_id: ShardIdentifier) -> Self: + """Return a new query, limited to a single shard ID. + + All subsequent operations with the returned query will + be against the single shard regardless of other state. + + The shard_id can be passed for a 2.0 style execution to the + bind_arguments dictionary of :meth:`.Session.execute`:: + + results = session.execute(stmt, bind_arguments={"shard_id": "my_shard"}) + + """ # noqa: E501 + return self.execution_options(_sa_shard_id=shard_id) + + +class ShardedSession(Session): + shard_chooser: ShardChooser + identity_chooser: IdentityChooser + execute_chooser: Callable[[ORMExecuteState], Iterable[Any]] + + def __init__( + self, + shard_chooser: ShardChooser, + identity_chooser: Optional[IdentityChooser] = None, + execute_chooser: Optional[ + Callable[[ORMExecuteState], Iterable[Any]] + ] = None, + shards: Optional[Dict[str, Any]] = None, + query_cls: Type[Query[_T]] = ShardedQuery, + *, + id_chooser: Optional[ + Callable[[Query[_T], Iterable[_T]], Iterable[Any]] + ] = None, + query_chooser: Optional[Callable[[Executable], Iterable[Any]]] = None, + **kwargs: Any, + ) -> None: + """Construct a ShardedSession. + + :param shard_chooser: A callable which, passed a Mapper, a mapped + instance, and possibly a SQL clause, returns a shard ID. This id + may be based off of the attributes present within the object, or on + some round-robin scheme. If the scheme is based on a selection, it + should set whatever state on the instance to mark it in the future as + participating in that shard. + + :param identity_chooser: A callable, passed a Mapper and primary key + argument, which should return a list of shard ids where this + primary key might reside. + + .. versionchanged:: 2.0 The ``identity_chooser`` parameter + supersedes the ``id_chooser`` parameter. + + :param execute_chooser: For a given :class:`.ORMExecuteState`, + returns the list of shard_ids + where the query should be issued. Results from all shards returned + will be combined together into a single listing. + + .. versionchanged:: 1.4 The ``execute_chooser`` parameter + supersedes the ``query_chooser`` parameter. + + :param shards: A dictionary of string shard names + to :class:`~sqlalchemy.engine.Engine` objects. + + """ + super().__init__(query_cls=query_cls, **kwargs) + + event.listen( + self, "do_orm_execute", execute_and_instances, retval=True + ) + self.shard_chooser = shard_chooser + + if id_chooser: + _id_chooser = id_chooser + util.warn_deprecated( + "The ``id_chooser`` parameter is deprecated; " + "please use ``identity_chooser``.", + "2.0", + ) + + def _legacy_identity_chooser( + mapper: Mapper[_T], + primary_key: _PKIdentityArgument, + *, + lazy_loaded_from: Optional[InstanceState[Any]], + execution_options: OrmExecuteOptionsParameter, + bind_arguments: _BindArguments, + **kw: Any, + ) -> Any: + q = self.query(mapper) + if lazy_loaded_from: + q = q._set_lazyload_from(lazy_loaded_from) + return _id_chooser(q, primary_key) + + self.identity_chooser = _legacy_identity_chooser + elif identity_chooser: + self.identity_chooser = identity_chooser + else: + raise exc.ArgumentError( + "identity_chooser or id_chooser is required" + ) + + if query_chooser: + _query_chooser = query_chooser + util.warn_deprecated( + "The ``query_chooser`` parameter is deprecated; " + "please use ``execute_chooser``.", + "1.4", + ) + if execute_chooser: + raise exc.ArgumentError( + "Can't pass query_chooser and execute_chooser " + "at the same time." + ) + + def _default_execute_chooser( + orm_context: ORMExecuteState, + ) -> Iterable[Any]: + return _query_chooser(orm_context.statement) + + if execute_chooser is None: + execute_chooser = _default_execute_chooser + + if execute_chooser is None: + raise exc.ArgumentError( + "execute_chooser or query_chooser is required" + ) + self.execute_chooser = execute_chooser + self.__shards: Dict[ShardIdentifier, _SessionBind] = {} + if shards is not None: + for k in shards: + self.bind_shard(k, shards[k]) + + def _identity_lookup( + self, + mapper: Mapper[_O], + primary_key_identity: Union[Any, Tuple[Any, ...]], + identity_token: Optional[Any] = None, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + lazy_loaded_from: Optional[InstanceState[Any]] = None, + execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT, + bind_arguments: Optional[_BindArguments] = None, + **kw: Any, + ) -> Union[Optional[_O], LoaderCallableStatus]: + """override the default :meth:`.Session._identity_lookup` method so + that we search for a given non-token primary key identity across all + possible identity tokens (e.g. shard ids). + + .. versionchanged:: 1.4 Moved :meth:`.Session._identity_lookup` from + the :class:`_query.Query` object to the :class:`.Session`. + + """ + + if identity_token is not None: + obj = super()._identity_lookup( + mapper, + primary_key_identity, + identity_token=identity_token, + **kw, + ) + + return obj + else: + for shard_id in self.identity_chooser( + mapper, + primary_key_identity, + lazy_loaded_from=lazy_loaded_from, + execution_options=execution_options, + bind_arguments=dict(bind_arguments) if bind_arguments else {}, + ): + obj2 = super()._identity_lookup( + mapper, + primary_key_identity, + identity_token=shard_id, + lazy_loaded_from=lazy_loaded_from, + **kw, + ) + if obj2 is not None: + return obj2 + + return None + + def _choose_shard_and_assign( + self, + mapper: Optional[_EntityBindKey[_O]], + instance: Any, + **kw: Any, + ) -> Any: + if instance is not None: + state = inspect(instance) + if state.key: + token = state.key[2] + assert token is not None + return token + elif state.identity_token: + return state.identity_token + + assert isinstance(mapper, Mapper) + shard_id = self.shard_chooser(mapper, instance, **kw) + if instance is not None: + state.identity_token = shard_id + return shard_id + + def connection_callable( + self, + mapper: Optional[Mapper[_T]] = None, + instance: Optional[Any] = None, + shard_id: Optional[ShardIdentifier] = None, + **kw: Any, + ) -> Connection: + """Provide a :class:`_engine.Connection` to use in the unit of work + flush process. + + """ + + if shard_id is None: + shard_id = self._choose_shard_and_assign(mapper, instance) + + if self.in_transaction(): + trans = self.get_transaction() + assert trans is not None + return trans.connection(mapper, shard_id=shard_id) + else: + bind = self.get_bind( + mapper=mapper, shard_id=shard_id, instance=instance + ) + + if isinstance(bind, Engine): + return bind.connect(**kw) + else: + assert isinstance(bind, Connection) + return bind + + def get_bind( + self, + mapper: Optional[_EntityBindKey[_O]] = None, + *, + shard_id: Optional[ShardIdentifier] = None, + instance: Optional[Any] = None, + clause: Optional[ClauseElement] = None, + **kw: Any, + ) -> _SessionBind: + if shard_id is None: + shard_id = self._choose_shard_and_assign( + mapper, instance=instance, clause=clause + ) + assert shard_id is not None + return self.__shards[shard_id] + + def bind_shard( + self, shard_id: ShardIdentifier, bind: Union[Engine, OptionEngine] + ) -> None: + self.__shards[shard_id] = bind + + +class set_shard_id(ORMOption): + """a loader option for statements to apply a specific shard id to the + primary query as well as for additional relationship and column + loaders. + + The :class:`_horizontal.set_shard_id` option may be applied using + the :meth:`_sql.Executable.options` method of any executable statement:: + + stmt = ( + select(MyObject) + .where(MyObject.name == "some name") + .options(set_shard_id("shard1")) + ) + + Above, the statement when invoked will limit to the "shard1" shard + identifier for the primary query as well as for all relationship and + column loading strategies, including eager loaders such as + :func:`_orm.selectinload`, deferred column loaders like :func:`_orm.defer`, + and the lazy relationship loader :func:`_orm.lazyload`. + + In this way, the :class:`_horizontal.set_shard_id` option has much wider + scope than using the "shard_id" argument within the + :paramref:`_orm.Session.execute.bind_arguments` dictionary. + + + .. versionadded:: 2.0.0 + + """ + + __slots__ = ("shard_id", "propagate_to_loaders") + + def __init__( + self, shard_id: ShardIdentifier, propagate_to_loaders: bool = True + ): + """Construct a :class:`_horizontal.set_shard_id` option. + + :param shard_id: shard identifier + :param propagate_to_loaders: if left at its default of ``True``, the + shard option will take place for lazy loaders such as + :func:`_orm.lazyload` and :func:`_orm.defer`; if False, the option + will not be propagated to loaded objects. Note that :func:`_orm.defer` + always limits to the shard_id of the parent row in any case, so the + parameter only has a net effect on the behavior of the + :func:`_orm.lazyload` strategy. + + """ + self.shard_id = shard_id + self.propagate_to_loaders = propagate_to_loaders + + +def execute_and_instances( + orm_context: ORMExecuteState, +) -> Union[Result[_T], IteratorResult[_TP]]: + active_options: Union[ + None, + QueryContext.default_load_options, + Type[QueryContext.default_load_options], + BulkUDCompileState.default_update_options, + Type[BulkUDCompileState.default_update_options], + ] + + if orm_context.is_select: + active_options = orm_context.load_options + + elif orm_context.is_update or orm_context.is_delete: + active_options = orm_context.update_delete_options + else: + active_options = None + + session = orm_context.session + assert isinstance(session, ShardedSession) + + def iter_for_shard( + shard_id: ShardIdentifier, + ) -> Union[Result[_T], IteratorResult[_TP]]: + bind_arguments = dict(orm_context.bind_arguments) + bind_arguments["shard_id"] = shard_id + + orm_context.update_execution_options(identity_token=shard_id) + return orm_context.invoke_statement(bind_arguments=bind_arguments) + + for orm_opt in orm_context._non_compile_orm_options: + # TODO: if we had an ORMOption that gets applied at ORM statement + # execution time, that would allow this to be more generalized. + # for now just iterate and look for our options + if isinstance(orm_opt, set_shard_id): + shard_id = orm_opt.shard_id + break + else: + if active_options and active_options._identity_token is not None: + shard_id = active_options._identity_token + elif "_sa_shard_id" in orm_context.execution_options: + shard_id = orm_context.execution_options["_sa_shard_id"] + elif "shard_id" in orm_context.bind_arguments: + shard_id = orm_context.bind_arguments["shard_id"] + else: + shard_id = None + + if shard_id is not None: + return iter_for_shard(shard_id) + else: + partial = [] + for shard_id in session.execute_chooser(orm_context): + result_ = iter_for_shard(shard_id) + partial.append(result_) + return partial[0].merge(*partial[1:]) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/hybrid.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebefb61ca69ce61350394c868742f1a8d6602a3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/hybrid.py @@ -0,0 +1,1535 @@ +# ext/hybrid.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +r"""Define attributes on ORM-mapped classes that have "hybrid" behavior. + +"hybrid" means the attribute has distinct behaviors defined at the +class level and at the instance level. + +The :mod:`~sqlalchemy.ext.hybrid` extension provides a special form of +method decorator and has minimal dependencies on the rest of SQLAlchemy. +Its basic theory of operation can work with any descriptor-based expression +system. + +Consider a mapping ``Interval``, representing integer ``start`` and ``end`` +values. We can define higher level functions on mapped classes that produce SQL +expressions at the class level, and Python expression evaluation at the +instance level. Below, each function decorated with :class:`.hybrid_method` or +:class:`.hybrid_property` may receive ``self`` as an instance of the class, or +may receive the class directly, depending on context:: + + from __future__ import annotations + + from sqlalchemy.ext.hybrid import hybrid_method + from sqlalchemy.ext.hybrid import hybrid_property + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + + + class Base(DeclarativeBase): + pass + + + class Interval(Base): + __tablename__ = "interval" + + id: Mapped[int] = mapped_column(primary_key=True) + start: Mapped[int] + end: Mapped[int] + + def __init__(self, start: int, end: int): + self.start = start + self.end = end + + @hybrid_property + def length(self) -> int: + return self.end - self.start + + @hybrid_method + def contains(self, point: int) -> bool: + return (self.start <= point) & (point <= self.end) + + @hybrid_method + def intersects(self, other: Interval) -> bool: + return self.contains(other.start) | self.contains(other.end) + +Above, the ``length`` property returns the difference between the +``end`` and ``start`` attributes. With an instance of ``Interval``, +this subtraction occurs in Python, using normal Python descriptor +mechanics:: + + >>> i1 = Interval(5, 10) + >>> i1.length + 5 + +When dealing with the ``Interval`` class itself, the :class:`.hybrid_property` +descriptor evaluates the function body given the ``Interval`` class as +the argument, which when evaluated with SQLAlchemy expression mechanics +returns a new SQL expression: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> print(select(Interval.length)) + {printsql}SELECT interval."end" - interval.start AS length + FROM interval{stop} + + + >>> print(select(Interval).filter(Interval.length > 10)) + {printsql}SELECT interval.id, interval.start, interval."end" + FROM interval + WHERE interval."end" - interval.start > :param_1 + +Filtering methods such as :meth:`.Select.filter_by` are supported +with hybrid attributes as well: + +.. sourcecode:: pycon+sql + + >>> print(select(Interval).filter_by(length=5)) + {printsql}SELECT interval.id, interval.start, interval."end" + FROM interval + WHERE interval."end" - interval.start = :param_1 + +The ``Interval`` class example also illustrates two methods, +``contains()`` and ``intersects()``, decorated with +:class:`.hybrid_method`. This decorator applies the same idea to +methods that :class:`.hybrid_property` applies to attributes. The +methods return boolean values, and take advantage of the Python ``|`` +and ``&`` bitwise operators to produce equivalent instance-level and +SQL expression-level boolean behavior: + +.. sourcecode:: pycon+sql + + >>> i1.contains(6) + True + >>> i1.contains(15) + False + >>> i1.intersects(Interval(7, 18)) + True + >>> i1.intersects(Interval(25, 29)) + False + + >>> print(select(Interval).filter(Interval.contains(15))) + {printsql}SELECT interval.id, interval.start, interval."end" + FROM interval + WHERE interval.start <= :start_1 AND interval."end" > :end_1{stop} + + >>> ia = aliased(Interval) + >>> print(select(Interval, ia).filter(Interval.intersects(ia))) + {printsql}SELECT interval.id, interval.start, + interval."end", interval_1.id AS interval_1_id, + interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end + FROM interval, interval AS interval_1 + WHERE interval.start <= interval_1.start + AND interval."end" > interval_1.start + OR interval.start <= interval_1."end" + AND interval."end" > interval_1."end"{stop} + +.. _hybrid_distinct_expression: + +Defining Expression Behavior Distinct from Attribute Behavior +-------------------------------------------------------------- + +In the previous section, our usage of the ``&`` and ``|`` bitwise operators +within the ``Interval.contains`` and ``Interval.intersects`` methods was +fortunate, considering our functions operated on two boolean values to return a +new one. In many cases, the construction of an in-Python function and a +SQLAlchemy SQL expression have enough differences that two separate Python +expressions should be defined. The :mod:`~sqlalchemy.ext.hybrid` decorator +defines a **modifier** :meth:`.hybrid_property.expression` for this purpose. As an +example we'll define the radius of the interval, which requires the usage of +the absolute value function:: + + from sqlalchemy import ColumnElement + from sqlalchemy import Float + from sqlalchemy import func + from sqlalchemy import type_coerce + + + class Interval(Base): + # ... + + @hybrid_property + def radius(self) -> float: + return abs(self.length) / 2 + + @radius.inplace.expression + @classmethod + def _radius_expression(cls) -> ColumnElement[float]: + return type_coerce(func.abs(cls.length) / 2, Float) + +In the above example, the :class:`.hybrid_property` first assigned to the +name ``Interval.radius`` is amended by a subsequent method called +``Interval._radius_expression``, using the decorator +``@radius.inplace.expression``, which chains together two modifiers +:attr:`.hybrid_property.inplace` and :attr:`.hybrid_property.expression`. +The use of :attr:`.hybrid_property.inplace` indicates that the +:meth:`.hybrid_property.expression` modifier should mutate the +existing hybrid object at ``Interval.radius`` in place, without creating a +new object. Notes on this modifier and its +rationale are discussed in the next section :ref:`hybrid_pep484_naming`. +The use of ``@classmethod`` is optional, and is strictly to give typing +tools a hint that ``cls`` in this case is expected to be the ``Interval`` +class, and not an instance of ``Interval``. + +.. note:: :attr:`.hybrid_property.inplace` as well as the use of ``@classmethod`` + for proper typing support are available as of SQLAlchemy 2.0.4, and will + not work in earlier versions. + +With ``Interval.radius`` now including an expression element, the SQL +function ``ABS()`` is returned when accessing ``Interval.radius`` +at the class level: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> print(select(Interval).filter(Interval.radius > 5)) + {printsql}SELECT interval.id, interval.start, interval."end" + FROM interval + WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1 + + +.. _hybrid_pep484_naming: + +Using ``inplace`` to create pep-484 compliant hybrid properties +--------------------------------------------------------------- + +In the previous section, a :class:`.hybrid_property` decorator is illustrated +which includes two separate method-level functions being decorated, both +to produce a single object attribute referenced as ``Interval.radius``. +There are actually several different modifiers we can use for +:class:`.hybrid_property` including :meth:`.hybrid_property.expression`, +:meth:`.hybrid_property.setter` and :meth:`.hybrid_property.update_expression`. + +SQLAlchemy's :class:`.hybrid_property` decorator intends that adding on these +methods may be done in the identical manner as Python's built-in +``@property`` decorator, where idiomatic use is to continue to redefine the +attribute repeatedly, using the **same attribute name** each time, as in the +example below that illustrates the use of :meth:`.hybrid_property.setter` and +:meth:`.hybrid_property.expression` for the ``Interval.radius`` descriptor:: + + # correct use, however is not accepted by pep-484 tooling + + + class Interval(Base): + # ... + + @hybrid_property + def radius(self): + return abs(self.length) / 2 + + @radius.setter + def radius(self, value): + self.length = value * 2 + + @radius.expression + def radius(cls): + return type_coerce(func.abs(cls.length) / 2, Float) + +Above, there are three ``Interval.radius`` methods, but as each are decorated, +first by the :class:`.hybrid_property` decorator and then by the +``@radius`` name itself, the end effect is that ``Interval.radius`` is +a single attribute with three different functions contained within it. +This style of use is taken from `Python's documented use of @property +`_. +It is important to note that the way both ``@property`` as well as +:class:`.hybrid_property` work, a **copy of the descriptor is made each time**. +That is, each call to ``@radius.expression``, ``@radius.setter`` etc. +make a new object entirely. This allows the attribute to be re-defined in +subclasses without issue (see :ref:`hybrid_reuse_subclass` later in this +section for how this is used). + +However, the above approach is not compatible with typing tools such as +mypy and pyright. Python's own ``@property`` decorator does not have this +limitation only because +`these tools hardcode the behavior of @property +`_, meaning this syntax +is not available to SQLAlchemy under :pep:`484` compliance. + +In order to produce a reasonable syntax while remaining typing compliant, +the :attr:`.hybrid_property.inplace` decorator allows the same +decorator to be reused with different method names, while still producing +a single decorator under one name:: + + # correct use which is also accepted by pep-484 tooling + + + class Interval(Base): + # ... + + @hybrid_property + def radius(self) -> float: + return abs(self.length) / 2 + + @radius.inplace.setter + def _radius_setter(self, value: float) -> None: + # for example only + self.length = value * 2 + + @radius.inplace.expression + @classmethod + def _radius_expression(cls) -> ColumnElement[float]: + return type_coerce(func.abs(cls.length) / 2, Float) + +Using :attr:`.hybrid_property.inplace` further qualifies the use of the +decorator that a new copy should not be made, thereby maintaining the +``Interval.radius`` name while allowing additional methods +``Interval._radius_setter`` and ``Interval._radius_expression`` to be +differently named. + + +.. versionadded:: 2.0.4 Added :attr:`.hybrid_property.inplace` to allow + less verbose construction of composite :class:`.hybrid_property` objects + while not having to use repeated method names. Additionally allowed the + use of ``@classmethod`` within :attr:`.hybrid_property.expression`, + :attr:`.hybrid_property.update_expression`, and + :attr:`.hybrid_property.comparator` to allow typing tools to identify + ``cls`` as a class and not an instance in the method signature. + + +Defining Setters +---------------- + +The :meth:`.hybrid_property.setter` modifier allows the construction of a +custom setter method, that can modify values on the object:: + + class Interval(Base): + # ... + + @hybrid_property + def length(self) -> int: + return self.end - self.start + + @length.inplace.setter + def _length_setter(self, value: int) -> None: + self.end = self.start + value + +The ``length(self, value)`` method is now called upon set:: + + >>> i1 = Interval(5, 10) + >>> i1.length + 5 + >>> i1.length = 12 + >>> i1.end + 17 + +.. _hybrid_bulk_update: + +Allowing Bulk ORM Update +------------------------ + +A hybrid can define a custom "UPDATE" handler for when using +ORM-enabled updates, allowing the hybrid to be used in the +SET clause of the update. + +Normally, when using a hybrid with :func:`_sql.update`, the SQL +expression is used as the column that's the target of the SET. If our +``Interval`` class had a hybrid ``start_point`` that linked to +``Interval.start``, this could be substituted directly:: + + from sqlalchemy import update + + stmt = update(Interval).values({Interval.start_point: 10}) + +However, when using a composite hybrid like ``Interval.length``, this +hybrid represents more than one column. We can set up a handler that will +accommodate a value passed in the VALUES expression which can affect +this, using the :meth:`.hybrid_property.update_expression` decorator. +A handler that works similarly to our setter would be:: + + from typing import List, Tuple, Any + + + class Interval(Base): + # ... + + @hybrid_property + def length(self) -> int: + return self.end - self.start + + @length.inplace.setter + def _length_setter(self, value: int) -> None: + self.end = self.start + value + + @length.inplace.update_expression + def _length_update_expression( + cls, value: Any + ) -> List[Tuple[Any, Any]]: + return [(cls.end, cls.start + value)] + +Above, if we use ``Interval.length`` in an UPDATE expression, we get +a hybrid SET expression: + +.. sourcecode:: pycon+sql + + + >>> from sqlalchemy import update + >>> print(update(Interval).values({Interval.length: 25})) + {printsql}UPDATE interval SET "end"=(interval.start + :start_1) + +This SET expression is accommodated by the ORM automatically. + +.. seealso:: + + :ref:`orm_expression_update_delete` - includes background on ORM-enabled + UPDATE statements + + +Working with Relationships +-------------------------- + +There's no essential difference when creating hybrids that work with +related objects as opposed to column-based data. The need for distinct +expressions tends to be greater. The two variants we'll illustrate +are the "join-dependent" hybrid, and the "correlated subquery" hybrid. + +Join-Dependent Relationship Hybrid +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Consider the following declarative +mapping which relates a ``User`` to a ``SavingsAccount``:: + + from __future__ import annotations + + from decimal import Decimal + from typing import cast + from typing import List + from typing import Optional + + from sqlalchemy import ForeignKey + from sqlalchemy import Numeric + from sqlalchemy import String + from sqlalchemy import SQLColumnExpression + from sqlalchemy.ext.hybrid import hybrid_property + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + from sqlalchemy.orm import relationship + + + class Base(DeclarativeBase): + pass + + + class SavingsAccount(Base): + __tablename__ = "account" + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("user.id")) + balance: Mapped[Decimal] = mapped_column(Numeric(15, 5)) + + owner: Mapped[User] = relationship(back_populates="accounts") + + + class User(Base): + __tablename__ = "user" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + + accounts: Mapped[List[SavingsAccount]] = relationship( + back_populates="owner", lazy="selectin" + ) + + @hybrid_property + def balance(self) -> Optional[Decimal]: + if self.accounts: + return self.accounts[0].balance + else: + return None + + @balance.inplace.setter + def _balance_setter(self, value: Optional[Decimal]) -> None: + assert value is not None + + if not self.accounts: + account = SavingsAccount(owner=self) + else: + account = self.accounts[0] + account.balance = value + + @balance.inplace.expression + @classmethod + def _balance_expression(cls) -> SQLColumnExpression[Optional[Decimal]]: + return cast( + "SQLColumnExpression[Optional[Decimal]]", + SavingsAccount.balance, + ) + +The above hybrid property ``balance`` works with the first +``SavingsAccount`` entry in the list of accounts for this user. The +in-Python getter/setter methods can treat ``accounts`` as a Python +list available on ``self``. + +.. tip:: The ``User.balance`` getter in the above example accesses the + ``self.accounts`` collection, which will normally be loaded via the + :func:`.selectinload` loader strategy configured on the ``User.balance`` + :func:`_orm.relationship`. The default loader strategy when not otherwise + stated on :func:`_orm.relationship` is :func:`.lazyload`, which emits SQL on + demand. When using asyncio, on-demand loaders such as :func:`.lazyload` are + not supported, so care should be taken to ensure the ``self.accounts`` + collection is accessible to this hybrid accessor when using asyncio. + +At the expression level, it's expected that the ``User`` class will +be used in an appropriate context such that an appropriate join to +``SavingsAccount`` will be present: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> print( + ... select(User, User.balance) + ... .join(User.accounts) + ... .filter(User.balance > 5000) + ... ) + {printsql}SELECT "user".id AS user_id, "user".name AS user_name, + account.balance AS account_balance + FROM "user" JOIN account ON "user".id = account.user_id + WHERE account.balance > :balance_1 + +Note however, that while the instance level accessors need to worry +about whether ``self.accounts`` is even present, this issue expresses +itself differently at the SQL expression level, where we basically +would use an outer join: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> from sqlalchemy import or_ + >>> print( + ... select(User, User.balance) + ... .outerjoin(User.accounts) + ... .filter(or_(User.balance < 5000, User.balance == None)) + ... ) + {printsql}SELECT "user".id AS user_id, "user".name AS user_name, + account.balance AS account_balance + FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id + WHERE account.balance < :balance_1 OR account.balance IS NULL + +Correlated Subquery Relationship Hybrid +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We can, of course, forego being dependent on the enclosing query's usage +of joins in favor of the correlated subquery, which can portably be packed +into a single column expression. A correlated subquery is more portable, but +often performs more poorly at the SQL level. Using the same technique +illustrated at :ref:`mapper_column_property_sql_expressions`, +we can adjust our ``SavingsAccount`` example to aggregate the balances for +*all* accounts, and use a correlated subquery for the column expression:: + + from __future__ import annotations + + from decimal import Decimal + from typing import List + + from sqlalchemy import ForeignKey + from sqlalchemy import func + from sqlalchemy import Numeric + from sqlalchemy import select + from sqlalchemy import SQLColumnExpression + from sqlalchemy import String + from sqlalchemy.ext.hybrid import hybrid_property + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + from sqlalchemy.orm import relationship + + + class Base(DeclarativeBase): + pass + + + class SavingsAccount(Base): + __tablename__ = "account" + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("user.id")) + balance: Mapped[Decimal] = mapped_column(Numeric(15, 5)) + + owner: Mapped[User] = relationship(back_populates="accounts") + + + class User(Base): + __tablename__ = "user" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + + accounts: Mapped[List[SavingsAccount]] = relationship( + back_populates="owner", lazy="selectin" + ) + + @hybrid_property + def balance(self) -> Decimal: + return sum( + (acc.balance for acc in self.accounts), start=Decimal("0") + ) + + @balance.inplace.expression + @classmethod + def _balance_expression(cls) -> SQLColumnExpression[Decimal]: + return ( + select(func.sum(SavingsAccount.balance)) + .where(SavingsAccount.user_id == cls.id) + .label("total_balance") + ) + +The above recipe will give us the ``balance`` column which renders +a correlated SELECT: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> print(select(User).filter(User.balance > 400)) + {printsql}SELECT "user".id, "user".name + FROM "user" + WHERE ( + SELECT sum(account.balance) AS sum_1 FROM account + WHERE account.user_id = "user".id + ) > :param_1 + + +.. _hybrid_custom_comparators: + +Building Custom Comparators +--------------------------- + +The hybrid property also includes a helper that allows construction of +custom comparators. A comparator object allows one to customize the +behavior of each SQLAlchemy expression operator individually. They +are useful when creating custom types that have some highly +idiosyncratic behavior on the SQL side. + +.. note:: The :meth:`.hybrid_property.comparator` decorator introduced + in this section **replaces** the use of the + :meth:`.hybrid_property.expression` decorator. + They cannot be used together. + +The example class below allows case-insensitive comparisons on the attribute +named ``word_insensitive``:: + + from __future__ import annotations + + from typing import Any + + from sqlalchemy import ColumnElement + from sqlalchemy import func + from sqlalchemy.ext.hybrid import Comparator + from sqlalchemy.ext.hybrid import hybrid_property + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + + + class Base(DeclarativeBase): + pass + + + class CaseInsensitiveComparator(Comparator[str]): + def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + return func.lower(self.__clause_element__()) == func.lower(other) + + + class SearchWord(Base): + __tablename__ = "searchword" + + id: Mapped[int] = mapped_column(primary_key=True) + word: Mapped[str] + + @hybrid_property + def word_insensitive(self) -> str: + return self.word.lower() + + @word_insensitive.inplace.comparator + @classmethod + def _word_insensitive_comparator(cls) -> CaseInsensitiveComparator: + return CaseInsensitiveComparator(cls.word) + +Above, SQL expressions against ``word_insensitive`` will apply the ``LOWER()`` +SQL function to both sides: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy import select + >>> print(select(SearchWord).filter_by(word_insensitive="Trucks")) + {printsql}SELECT searchword.id, searchword.word + FROM searchword + WHERE lower(searchword.word) = lower(:lower_1) + + +The ``CaseInsensitiveComparator`` above implements part of the +:class:`.ColumnOperators` interface. A "coercion" operation like +lowercasing can be applied to all comparison operations (i.e. ``eq``, +``lt``, ``gt``, etc.) using :meth:`.Operators.operate`:: + + class CaseInsensitiveComparator(Comparator): + def operate(self, op, other, **kwargs): + return op( + func.lower(self.__clause_element__()), + func.lower(other), + **kwargs, + ) + +.. _hybrid_reuse_subclass: + +Reusing Hybrid Properties across Subclasses +------------------------------------------- + +A hybrid can be referred to from a superclass, to allow modifying +methods like :meth:`.hybrid_property.getter`, :meth:`.hybrid_property.setter` +to be used to redefine those methods on a subclass. This is similar to +how the standard Python ``@property`` object works:: + + class FirstNameOnly(Base): + # ... + + first_name: Mapped[str] + + @hybrid_property + def name(self) -> str: + return self.first_name + + @name.inplace.setter + def _name_setter(self, value: str) -> None: + self.first_name = value + + + class FirstNameLastName(FirstNameOnly): + # ... + + last_name: Mapped[str] + + # 'inplace' is not used here; calling getter creates a copy + # of FirstNameOnly.name that is local to FirstNameLastName + @FirstNameOnly.name.getter + def name(self) -> str: + return self.first_name + " " + self.last_name + + @name.inplace.setter + def _name_setter(self, value: str) -> None: + self.first_name, self.last_name = value.split(" ", 1) + +Above, the ``FirstNameLastName`` class refers to the hybrid from +``FirstNameOnly.name`` to repurpose its getter and setter for the subclass. + +When overriding :meth:`.hybrid_property.expression` and +:meth:`.hybrid_property.comparator` alone as the first reference to the +superclass, these names conflict with the same-named accessors on the class- +level :class:`.QueryableAttribute` object returned at the class level. To +override these methods when referring directly to the parent class descriptor, +add the special qualifier :attr:`.hybrid_property.overrides`, which will de- +reference the instrumented attribute back to the hybrid object:: + + class FirstNameLastName(FirstNameOnly): + # ... + + last_name: Mapped[str] + + @FirstNameOnly.name.overrides.expression + @classmethod + def name(cls): + return func.concat(cls.first_name, " ", cls.last_name) + +Hybrid Value Objects +-------------------- + +Note in our previous example, if we were to compare the ``word_insensitive`` +attribute of a ``SearchWord`` instance to a plain Python string, the plain +Python string would not be coerced to lower case - the +``CaseInsensitiveComparator`` we built, being returned by +``@word_insensitive.comparator``, only applies to the SQL side. + +A more comprehensive form of the custom comparator is to construct a *Hybrid +Value Object*. This technique applies the target value or expression to a value +object which is then returned by the accessor in all cases. The value object +allows control of all operations upon the value as well as how compared values +are treated, both on the SQL expression side as well as the Python value side. +Replacing the previous ``CaseInsensitiveComparator`` class with a new +``CaseInsensitiveWord`` class:: + + class CaseInsensitiveWord(Comparator): + "Hybrid value representing a lower case representation of a word." + + def __init__(self, word): + if isinstance(word, basestring): + self.word = word.lower() + elif isinstance(word, CaseInsensitiveWord): + self.word = word.word + else: + self.word = func.lower(word) + + def operate(self, op, other, **kwargs): + if not isinstance(other, CaseInsensitiveWord): + other = CaseInsensitiveWord(other) + return op(self.word, other.word, **kwargs) + + def __clause_element__(self): + return self.word + + def __str__(self): + return self.word + + key = "word" + "Label to apply to Query tuple results" + +Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may +be a SQL function, or may be a Python native. By overriding ``operate()`` and +``__clause_element__()`` to work in terms of ``self.word``, all comparison +operations will work against the "converted" form of ``word``, whether it be +SQL side or Python side. Our ``SearchWord`` class can now deliver the +``CaseInsensitiveWord`` object unconditionally from a single hybrid call:: + + class SearchWord(Base): + __tablename__ = "searchword" + id: Mapped[int] = mapped_column(primary_key=True) + word: Mapped[str] + + @hybrid_property + def word_insensitive(self) -> CaseInsensitiveWord: + return CaseInsensitiveWord(self.word) + +The ``word_insensitive`` attribute now has case-insensitive comparison behavior +universally, including SQL expression vs. Python expression (note the Python +value is converted to lower case on the Python side here): + +.. sourcecode:: pycon+sql + + >>> print(select(SearchWord).filter_by(word_insensitive="Trucks")) + {printsql}SELECT searchword.id AS searchword_id, searchword.word AS searchword_word + FROM searchword + WHERE lower(searchword.word) = :lower_1 + +SQL expression versus SQL expression: + +.. sourcecode:: pycon+sql + + >>> from sqlalchemy.orm import aliased + >>> sw1 = aliased(SearchWord) + >>> sw2 = aliased(SearchWord) + >>> print( + ... select(sw1.word_insensitive, sw2.word_insensitive).filter( + ... sw1.word_insensitive > sw2.word_insensitive + ... ) + ... ) + {printsql}SELECT lower(searchword_1.word) AS lower_1, + lower(searchword_2.word) AS lower_2 + FROM searchword AS searchword_1, searchword AS searchword_2 + WHERE lower(searchword_1.word) > lower(searchword_2.word) + +Python only expression:: + + >>> ws1 = SearchWord(word="SomeWord") + >>> ws1.word_insensitive == "sOmEwOrD" + True + >>> ws1.word_insensitive == "XOmEwOrX" + False + >>> print(ws1.word_insensitive) + someword + +The Hybrid Value pattern is very useful for any kind of value that may have +multiple representations, such as timestamps, time deltas, units of +measurement, currencies and encrypted passwords. + +.. seealso:: + + `Hybrids and Value Agnostic Types + `_ + - on the techspot.zzzeek.org blog + + `Value Agnostic Types, Part II + `_ - + on the techspot.zzzeek.org blog + + +""" # noqa + +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import cast +from typing import Generic +from typing import List +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .. import util +from ..orm import attributes +from ..orm import InspectionAttrExtensionType +from ..orm import interfaces +from ..orm import ORMDescriptor +from ..orm.attributes import QueryableAttribute +from ..sql import roles +from ..sql._typing import is_has_clause_element +from ..sql.elements import ColumnElement +from ..sql.elements import SQLCoreOperations +from ..util.typing import Concatenate +from ..util.typing import Literal +from ..util.typing import ParamSpec +from ..util.typing import Protocol +from ..util.typing import Self + +if TYPE_CHECKING: + from ..orm.interfaces import MapperProperty + from ..orm.util import AliasedInsp + from ..sql import SQLColumnExpression + from ..sql._typing import _ColumnExpressionArgument + from ..sql._typing import _DMLColumnArgument + from ..sql._typing import _HasClauseElement + from ..sql._typing import _InfoType + from ..sql.operators import OperatorType + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T", bound=Any) +_TE = TypeVar("_TE", bound=Any) +_T_co = TypeVar("_T_co", bound=Any, covariant=True) +_T_con = TypeVar("_T_con", bound=Any, contravariant=True) + + +class HybridExtensionType(InspectionAttrExtensionType): + HYBRID_METHOD = "HYBRID_METHOD" + """Symbol indicating an :class:`InspectionAttr` that's + of type :class:`.hybrid_method`. + + Is assigned to the :attr:`.InspectionAttr.extension_type` + attribute. + + .. seealso:: + + :attr:`_orm.Mapper.all_orm_attributes` + + """ + + HYBRID_PROPERTY = "HYBRID_PROPERTY" + """Symbol indicating an :class:`InspectionAttr` that's + of type :class:`.hybrid_method`. + + Is assigned to the :attr:`.InspectionAttr.extension_type` + attribute. + + .. seealso:: + + :attr:`_orm.Mapper.all_orm_attributes` + + """ + + +class _HybridGetterType(Protocol[_T_co]): + def __call__(s, __self: Any) -> _T_co: ... + + +class _HybridSetterType(Protocol[_T_con]): + def __call__(s, __self: Any, value: _T_con) -> None: ... + + +class _HybridUpdaterType(Protocol[_T_con]): + def __call__( + s, + cls: Any, + value: Union[_T_con, _ColumnExpressionArgument[_T_con]], + ) -> List[Tuple[_DMLColumnArgument, Any]]: ... + + +class _HybridDeleterType(Protocol[_T_co]): + def __call__(s, __self: Any) -> None: ... + + +class _HybridExprCallableType(Protocol[_T_co]): + def __call__( + s, __cls: Any + ) -> Union[_HasClauseElement[_T_co], SQLColumnExpression[_T_co]]: ... + + +class _HybridComparatorCallableType(Protocol[_T]): + def __call__(self, cls: Any) -> Comparator[_T]: ... + + +class _HybridClassLevelAccessor(QueryableAttribute[_T]): + """Describe the object returned by a hybrid_property() when + called as a class-level descriptor. + + """ + + if TYPE_CHECKING: + + def getter( + self, fget: _HybridGetterType[_T] + ) -> hybrid_property[_T]: ... + + def setter( + self, fset: _HybridSetterType[_T] + ) -> hybrid_property[_T]: ... + + def deleter( + self, fdel: _HybridDeleterType[_T] + ) -> hybrid_property[_T]: ... + + @property + def overrides(self) -> hybrid_property[_T]: ... + + def update_expression( + self, meth: _HybridUpdaterType[_T] + ) -> hybrid_property[_T]: ... + + +class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]): + """A decorator which allows definition of a Python object method with both + instance-level and class-level behavior. + + """ + + is_attribute = True + extension_type = HybridExtensionType.HYBRID_METHOD + + def __init__( + self, + func: Callable[Concatenate[Any, _P], _R], + expr: Optional[ + Callable[Concatenate[Any, _P], SQLCoreOperations[_R]] + ] = None, + ): + """Create a new :class:`.hybrid_method`. + + Usage is typically via decorator:: + + from sqlalchemy.ext.hybrid import hybrid_method + + + class SomeClass: + @hybrid_method + def value(self, x, y): + return self._value + x + y + + @value.expression + @classmethod + def value(cls, x, y): + return func.some_function(cls._value, x, y) + + """ + self.func = func + if expr is not None: + self.expression(expr) + else: + self.expression(func) # type: ignore + + @property + def inplace(self) -> Self: + """Return the inplace mutator for this :class:`.hybrid_method`. + + The :class:`.hybrid_method` class already performs "in place" mutation + when the :meth:`.hybrid_method.expression` decorator is called, + so this attribute returns Self. + + .. versionadded:: 2.0.4 + + .. seealso:: + + :ref:`hybrid_pep484_naming` + + """ + return self + + @overload + def __get__( + self, instance: Literal[None], owner: Type[object] + ) -> Callable[_P, SQLCoreOperations[_R]]: ... + + @overload + def __get__( + self, instance: object, owner: Type[object] + ) -> Callable[_P, _R]: ... + + def __get__( + self, instance: Optional[object], owner: Type[object] + ) -> Union[Callable[_P, _R], Callable[_P, SQLCoreOperations[_R]]]: + if instance is None: + return self.expr.__get__(owner, owner) # type: ignore + else: + return self.func.__get__(instance, owner) # type: ignore + + def expression( + self, expr: Callable[Concatenate[Any, _P], SQLCoreOperations[_R]] + ) -> hybrid_method[_P, _R]: + """Provide a modifying decorator that defines a + SQL-expression producing method.""" + + self.expr = expr + if not self.expr.__doc__: + self.expr.__doc__ = self.func.__doc__ + return self + + +def _unwrap_classmethod(meth: _T) -> _T: + if isinstance(meth, classmethod): + return meth.__func__ # type: ignore + else: + return meth + + +class hybrid_property(interfaces.InspectionAttrInfo, ORMDescriptor[_T]): + """A decorator which allows definition of a Python descriptor with both + instance-level and class-level behavior. + + """ + + is_attribute = True + extension_type = HybridExtensionType.HYBRID_PROPERTY + + __name__: str + + def __init__( + self, + fget: _HybridGetterType[_T], + fset: Optional[_HybridSetterType[_T]] = None, + fdel: Optional[_HybridDeleterType[_T]] = None, + expr: Optional[_HybridExprCallableType[_T]] = None, + custom_comparator: Optional[Comparator[_T]] = None, + update_expr: Optional[_HybridUpdaterType[_T]] = None, + ): + """Create a new :class:`.hybrid_property`. + + Usage is typically via decorator:: + + from sqlalchemy.ext.hybrid import hybrid_property + + + class SomeClass: + @hybrid_property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + + """ + self.fget = fget + self.fset = fset + self.fdel = fdel + self.expr = _unwrap_classmethod(expr) + self.custom_comparator = _unwrap_classmethod(custom_comparator) + self.update_expr = _unwrap_classmethod(update_expr) + util.update_wrapper(self, fget) # type: ignore[arg-type] + + @overload + def __get__(self, instance: Any, owner: Literal[None]) -> Self: ... + + @overload + def __get__( + self, instance: Literal[None], owner: Type[object] + ) -> _HybridClassLevelAccessor[_T]: ... + + @overload + def __get__(self, instance: object, owner: Type[object]) -> _T: ... + + def __get__( + self, instance: Optional[object], owner: Optional[Type[object]] + ) -> Union[hybrid_property[_T], _HybridClassLevelAccessor[_T], _T]: + if owner is None: + return self + elif instance is None: + return self._expr_comparator(owner) + else: + return self.fget(instance) + + def __set__( + self, instance: object, value: Union[SQLCoreOperations[_T], _T] + ) -> None: + if self.fset is None: + raise AttributeError("can't set attribute") + self.fset(instance, value) # type: ignore[arg-type] + + def __delete__(self, instance: object) -> None: + if self.fdel is None: + raise AttributeError("can't delete attribute") + self.fdel(instance) + + def _copy(self, **kw: Any) -> hybrid_property[_T]: + defaults = { + key: value + for key, value in self.__dict__.items() + if not key.startswith("_") + } + defaults.update(**kw) + return type(self)(**defaults) + + @property + def overrides(self) -> Self: + """Prefix for a method that is overriding an existing attribute. + + The :attr:`.hybrid_property.overrides` accessor just returns + this hybrid object, which when called at the class level from + a parent class, will de-reference the "instrumented attribute" + normally returned at this level, and allow modifying decorators + like :meth:`.hybrid_property.expression` and + :meth:`.hybrid_property.comparator` + to be used without conflicting with the same-named attributes + normally present on the :class:`.QueryableAttribute`:: + + class SuperClass: + # ... + + @hybrid_property + def foobar(self): + return self._foobar + + + class SubClass(SuperClass): + # ... + + @SuperClass.foobar.overrides.expression + def foobar(cls): + return func.subfoobar(self._foobar) + + .. versionadded:: 1.2 + + .. seealso:: + + :ref:`hybrid_reuse_subclass` + + """ + return self + + class _InPlace(Generic[_TE]): + """A builder helper for .hybrid_property. + + .. versionadded:: 2.0.4 + + """ + + __slots__ = ("attr",) + + def __init__(self, attr: hybrid_property[_TE]): + self.attr = attr + + def _set(self, **kw: Any) -> hybrid_property[_TE]: + for k, v in kw.items(): + setattr(self.attr, k, _unwrap_classmethod(v)) + return self.attr + + def getter(self, fget: _HybridGetterType[_TE]) -> hybrid_property[_TE]: + return self._set(fget=fget) + + def setter(self, fset: _HybridSetterType[_TE]) -> hybrid_property[_TE]: + return self._set(fset=fset) + + def deleter( + self, fdel: _HybridDeleterType[_TE] + ) -> hybrid_property[_TE]: + return self._set(fdel=fdel) + + def expression( + self, expr: _HybridExprCallableType[_TE] + ) -> hybrid_property[_TE]: + return self._set(expr=expr) + + def comparator( + self, comparator: _HybridComparatorCallableType[_TE] + ) -> hybrid_property[_TE]: + return self._set(custom_comparator=comparator) + + def update_expression( + self, meth: _HybridUpdaterType[_TE] + ) -> hybrid_property[_TE]: + return self._set(update_expr=meth) + + @property + def inplace(self) -> _InPlace[_T]: + """Return the inplace mutator for this :class:`.hybrid_property`. + + This is to allow in-place mutation of the hybrid, allowing the first + hybrid method of a certain name to be reused in order to add + more methods without having to name those methods the same, e.g.:: + + class Interval(Base): + # ... + + @hybrid_property + def radius(self) -> float: + return abs(self.length) / 2 + + @radius.inplace.setter + def _radius_setter(self, value: float) -> None: + self.length = value * 2 + + @radius.inplace.expression + def _radius_expression(cls) -> ColumnElement[float]: + return type_coerce(func.abs(cls.length) / 2, Float) + + .. versionadded:: 2.0.4 + + .. seealso:: + + :ref:`hybrid_pep484_naming` + + """ + return hybrid_property._InPlace(self) + + def getter(self, fget: _HybridGetterType[_T]) -> hybrid_property[_T]: + """Provide a modifying decorator that defines a getter method. + + .. versionadded:: 1.2 + + """ + + return self._copy(fget=fget) + + def setter(self, fset: _HybridSetterType[_T]) -> hybrid_property[_T]: + """Provide a modifying decorator that defines a setter method.""" + + return self._copy(fset=fset) + + def deleter(self, fdel: _HybridDeleterType[_T]) -> hybrid_property[_T]: + """Provide a modifying decorator that defines a deletion method.""" + + return self._copy(fdel=fdel) + + def expression( + self, expr: _HybridExprCallableType[_T] + ) -> hybrid_property[_T]: + """Provide a modifying decorator that defines a SQL-expression + producing method. + + When a hybrid is invoked at the class level, the SQL expression given + here is wrapped inside of a specialized :class:`.QueryableAttribute`, + which is the same kind of object used by the ORM to represent other + mapped attributes. The reason for this is so that other class-level + attributes such as docstrings and a reference to the hybrid itself may + be maintained within the structure that's returned, without any + modifications to the original SQL expression passed in. + + .. note:: + + When referring to a hybrid property from an owning class (e.g. + ``SomeClass.some_hybrid``), an instance of + :class:`.QueryableAttribute` is returned, representing the + expression or comparator object as well as this hybrid object. + However, that object itself has accessors called ``expression`` and + ``comparator``; so when attempting to override these decorators on a + subclass, it may be necessary to qualify it using the + :attr:`.hybrid_property.overrides` modifier first. See that + modifier for details. + + .. seealso:: + + :ref:`hybrid_distinct_expression` + + """ + + return self._copy(expr=expr) + + def comparator( + self, comparator: _HybridComparatorCallableType[_T] + ) -> hybrid_property[_T]: + """Provide a modifying decorator that defines a custom + comparator producing method. + + The return value of the decorated method should be an instance of + :class:`~.hybrid.Comparator`. + + .. note:: The :meth:`.hybrid_property.comparator` decorator + **replaces** the use of the :meth:`.hybrid_property.expression` + decorator. They cannot be used together. + + When a hybrid is invoked at the class level, the + :class:`~.hybrid.Comparator` object given here is wrapped inside of a + specialized :class:`.QueryableAttribute`, which is the same kind of + object used by the ORM to represent other mapped attributes. The + reason for this is so that other class-level attributes such as + docstrings and a reference to the hybrid itself may be maintained + within the structure that's returned, without any modifications to the + original comparator object passed in. + + .. note:: + + When referring to a hybrid property from an owning class (e.g. + ``SomeClass.some_hybrid``), an instance of + :class:`.QueryableAttribute` is returned, representing the + expression or comparator object as this hybrid object. However, + that object itself has accessors called ``expression`` and + ``comparator``; so when attempting to override these decorators on a + subclass, it may be necessary to qualify it using the + :attr:`.hybrid_property.overrides` modifier first. See that + modifier for details. + + """ + return self._copy(custom_comparator=comparator) + + def update_expression( + self, meth: _HybridUpdaterType[_T] + ) -> hybrid_property[_T]: + """Provide a modifying decorator that defines an UPDATE tuple + producing method. + + The method accepts a single value, which is the value to be + rendered into the SET clause of an UPDATE statement. The method + should then process this value into individual column expressions + that fit into the ultimate SET clause, and return them as a + sequence of 2-tuples. Each tuple + contains a column expression as the key and a value to be rendered. + + E.g.:: + + class Person(Base): + # ... + + first_name = Column(String) + last_name = Column(String) + + @hybrid_property + def fullname(self): + return first_name + " " + last_name + + @fullname.update_expression + def fullname(cls, value): + fname, lname = value.split(" ", 1) + return [(cls.first_name, fname), (cls.last_name, lname)] + + .. versionadded:: 1.2 + + """ + return self._copy(update_expr=meth) + + @util.memoized_property + def _expr_comparator( + self, + ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]: + if self.custom_comparator is not None: + return self._get_comparator(self.custom_comparator) + elif self.expr is not None: + return self._get_expr(self.expr) + else: + return self._get_expr(cast(_HybridExprCallableType[_T], self.fget)) + + def _get_expr( + self, expr: _HybridExprCallableType[_T] + ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]: + def _expr(cls: Any) -> ExprComparator[_T]: + return ExprComparator(cls, expr(cls), self) + + util.update_wrapper(_expr, expr) + + return self._get_comparator(_expr) + + def _get_comparator( + self, comparator: Any + ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]: + proxy_attr = attributes.create_proxied_attribute(self) + + def expr_comparator( + owner: Type[object], + ) -> _HybridClassLevelAccessor[_T]: + # because this is the descriptor protocol, we don't really know + # what our attribute name is. so search for it through the + # MRO. + for lookup in owner.__mro__: + if self.__name__ in lookup.__dict__: + if lookup.__dict__[self.__name__] is self: + name = self.__name__ + break + else: + name = attributes._UNKNOWN_ATTR_KEY # type: ignore[assignment,unused-ignore] # noqa: E501 + + return cast( + "_HybridClassLevelAccessor[_T]", + proxy_attr( + owner, + name, + self, + comparator(owner), + doc=comparator.__doc__ or self.__doc__, + ), + ) + + return expr_comparator + + +class Comparator(interfaces.PropComparator[_T]): + """A helper class that allows easy construction of custom + :class:`~.orm.interfaces.PropComparator` + classes for usage with hybrids.""" + + def __init__( + self, expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]] + ): + self.expression = expression + + def __clause_element__(self) -> roles.ColumnsClauseRole: + expr = self.expression + if is_has_clause_element(expr): + ret_expr = expr.__clause_element__() + else: + if TYPE_CHECKING: + assert isinstance(expr, ColumnElement) + ret_expr = expr + + if TYPE_CHECKING: + # see test_hybrid->test_expression_isnt_clause_element + # that exercises the usual place this is caught if not + # true + assert isinstance(ret_expr, ColumnElement) + return ret_expr + + @util.non_memoized_property + def property(self) -> interfaces.MapperProperty[_T]: + raise NotImplementedError() + + def adapt_to_entity( + self, adapt_to_entity: AliasedInsp[Any] + ) -> Comparator[_T]: + # interesting.... + return self + + +class ExprComparator(Comparator[_T]): + def __init__( + self, + cls: Type[Any], + expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]], + hybrid: hybrid_property[_T], + ): + self.cls = cls + self.expression = expression + self.hybrid = hybrid + + def __getattr__(self, key: str) -> Any: + return getattr(self.expression, key) + + @util.ro_non_memoized_property + def info(self) -> _InfoType: + return self.hybrid.info + + def _bulk_update_tuples( + self, value: Any + ) -> Sequence[Tuple[_DMLColumnArgument, Any]]: + if isinstance(self.expression, attributes.QueryableAttribute): + return self.expression._bulk_update_tuples(value) + elif self.hybrid.update_expr is not None: + return self.hybrid.update_expr(self.cls, value) + else: + return [(self.expression, value)] + + @util.non_memoized_property + def property(self) -> MapperProperty[_T]: + # this accessor is not normally used, however is accessed by things + # like ORM synonyms if the hybrid is used in this context; the + # .property attribute is not necessarily accessible + return self.expression.property # type: ignore + + def operate( + self, op: OperatorType, *other: Any, **kwargs: Any + ) -> ColumnElement[Any]: + return op(self.expression, *other, **kwargs) + + def reverse_operate( + self, op: OperatorType, other: Any, **kwargs: Any + ) -> ColumnElement[Any]: + return op(other, self.expression, **kwargs) # type: ignore diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/indexable.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/indexable.py new file mode 100644 index 0000000000000000000000000000000000000000..5248b5e54672a86453f487024fc5cb9ae742a687 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/indexable.py @@ -0,0 +1,364 @@ +# ext/indexable.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Define attributes on ORM-mapped classes that have "index" attributes for +columns with :class:`_types.Indexable` types. + +"index" means the attribute is associated with an element of an +:class:`_types.Indexable` column with the predefined index to access it. +The :class:`_types.Indexable` types include types such as +:class:`_types.ARRAY`, :class:`_types.JSON` and +:class:`_postgresql.HSTORE`. + + + +The :mod:`~sqlalchemy.ext.indexable` extension provides +:class:`_schema.Column`-like interface for any element of an +:class:`_types.Indexable` typed column. In simple cases, it can be +treated as a :class:`_schema.Column` - mapped attribute. + +Synopsis +======== + +Given ``Person`` as a model with a primary key and JSON data field. +While this field may have any number of elements encoded within it, +we would like to refer to the element called ``name`` individually +as a dedicated attribute which behaves like a standalone column:: + + from sqlalchemy import Column, JSON, Integer + from sqlalchemy.ext.declarative import declarative_base + from sqlalchemy.ext.indexable import index_property + + Base = declarative_base() + + + class Person(Base): + __tablename__ = "person" + + id = Column(Integer, primary_key=True) + data = Column(JSON) + + name = index_property("data", "name") + +Above, the ``name`` attribute now behaves like a mapped column. We +can compose a new ``Person`` and set the value of ``name``:: + + >>> person = Person(name="Alchemist") + +The value is now accessible:: + + >>> person.name + 'Alchemist' + +Behind the scenes, the JSON field was initialized to a new blank dictionary +and the field was set:: + + >>> person.data + {'name': 'Alchemist'} + +The field is mutable in place:: + + >>> person.name = "Renamed" + >>> person.name + 'Renamed' + >>> person.data + {'name': 'Renamed'} + +When using :class:`.index_property`, the change that we make to the indexable +structure is also automatically tracked as history; we no longer need +to use :class:`~.mutable.MutableDict` in order to track this change +for the unit of work. + +Deletions work normally as well:: + + >>> del person.name + >>> person.data + {} + +Above, deletion of ``person.name`` deletes the value from the dictionary, +but not the dictionary itself. + +A missing key will produce ``AttributeError``:: + + >>> person = Person() + >>> person.name + AttributeError: 'name' + +Unless you set a default value:: + + >>> class Person(Base): + ... __tablename__ = "person" + ... + ... id = Column(Integer, primary_key=True) + ... data = Column(JSON) + ... + ... name = index_property("data", "name", default=None) # See default + + >>> person = Person() + >>> print(person.name) + None + + +The attributes are also accessible at the class level. +Below, we illustrate ``Person.name`` used to generate +an indexed SQL criteria:: + + >>> from sqlalchemy.orm import Session + >>> session = Session() + >>> query = session.query(Person).filter(Person.name == "Alchemist") + +The above query is equivalent to:: + + >>> query = session.query(Person).filter(Person.data["name"] == "Alchemist") + +Multiple :class:`.index_property` objects can be chained to produce +multiple levels of indexing:: + + from sqlalchemy import Column, JSON, Integer + from sqlalchemy.ext.declarative import declarative_base + from sqlalchemy.ext.indexable import index_property + + Base = declarative_base() + + + class Person(Base): + __tablename__ = "person" + + id = Column(Integer, primary_key=True) + data = Column(JSON) + + birthday = index_property("data", "birthday") + year = index_property("birthday", "year") + month = index_property("birthday", "month") + day = index_property("birthday", "day") + +Above, a query such as:: + + q = session.query(Person).filter(Person.year == "1980") + +On a PostgreSQL backend, the above query will render as: + +.. sourcecode:: sql + + SELECT person.id, person.data + FROM person + WHERE person.data -> %(data_1)s -> %(param_1)s = %(param_2)s + +Default Values +============== + +:class:`.index_property` includes special behaviors for when the indexed +data structure does not exist, and a set operation is called: + +* For an :class:`.index_property` that is given an integer index value, + the default data structure will be a Python list of ``None`` values, + at least as long as the index value; the value is then set at its + place in the list. This means for an index value of zero, the list + will be initialized to ``[None]`` before setting the given value, + and for an index value of five, the list will be initialized to + ``[None, None, None, None, None]`` before setting the fifth element + to the given value. Note that an existing list is **not** extended + in place to receive a value. + +* for an :class:`.index_property` that is given any other kind of index + value (e.g. strings usually), a Python dictionary is used as the + default data structure. + +* The default data structure can be set to any Python callable using the + :paramref:`.index_property.datatype` parameter, overriding the previous + rules. + + +Subclassing +=========== + +:class:`.index_property` can be subclassed, in particular for the common +use case of providing coercion of values or SQL expressions as they are +accessed. Below is a common recipe for use with a PostgreSQL JSON type, +where we want to also include automatic casting plus ``astext()``:: + + class pg_json_property(index_property): + def __init__(self, attr_name, index, cast_type): + super(pg_json_property, self).__init__(attr_name, index) + self.cast_type = cast_type + + def expr(self, model): + expr = super(pg_json_property, self).expr(model) + return expr.astext.cast(self.cast_type) + +The above subclass can be used with the PostgreSQL-specific +version of :class:`_postgresql.JSON`:: + + from sqlalchemy import Column, Integer + from sqlalchemy.ext.declarative import declarative_base + from sqlalchemy.dialects.postgresql import JSON + + Base = declarative_base() + + + class Person(Base): + __tablename__ = "person" + + id = Column(Integer, primary_key=True) + data = Column(JSON) + + age = pg_json_property("data", "age", Integer) + +The ``age`` attribute at the instance level works as before; however +when rendering SQL, PostgreSQL's ``->>`` operator will be used +for indexed access, instead of the usual index operator of ``->``:: + + >>> query = session.query(Person).filter(Person.age < 20) + +The above query will render: + +.. sourcecode:: sql + + SELECT person.id, person.data + FROM person + WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s + +""" # noqa + +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import cast +from typing import Optional +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from .. import inspect +from ..ext.hybrid import hybrid_property +from ..orm.attributes import flag_modified + +if TYPE_CHECKING: + from ..sql import SQLColumnExpression + from ..sql._typing import _HasClauseElement + + +__all__ = ["index_property"] + +_T = TypeVar("_T") + + +class index_property(hybrid_property[_T]): + """A property generator. The generated property describes an object + attribute that corresponds to an :class:`_types.Indexable` + column. + + .. seealso:: + + :mod:`sqlalchemy.ext.indexable` + + """ + + _NO_DEFAULT_ARGUMENT = cast(_T, object()) + + def __init__( + self, + attr_name: str, + index: Union[int, str], + default: _T = _NO_DEFAULT_ARGUMENT, + datatype: Optional[Callable[[], Any]] = None, + mutable: bool = True, + onebased: bool = True, + ): + """Create a new :class:`.index_property`. + + :param attr_name: + An attribute name of an `Indexable` typed column, or other + attribute that returns an indexable structure. + :param index: + The index to be used for getting and setting this value. This + should be the Python-side index value for integers. + :param default: + A value which will be returned instead of `AttributeError` + when there is not a value at given index. + :param datatype: default datatype to use when the field is empty. + By default, this is derived from the type of index used; a + Python list for an integer index, or a Python dictionary for + any other style of index. For a list, the list will be + initialized to a list of None values that is at least + ``index`` elements long. + :param mutable: if False, writes and deletes to the attribute will + be disallowed. + :param onebased: assume the SQL representation of this value is + one-based; that is, the first index in SQL is 1, not zero. + """ + + if mutable: + super().__init__(self.fget, self.fset, self.fdel, self.expr) + else: + super().__init__(self.fget, None, None, self.expr) + self.attr_name = attr_name + self.index = index + self.default = default + is_numeric = isinstance(index, int) + onebased = is_numeric and onebased + + if datatype is not None: + self.datatype = datatype + else: + if is_numeric: + self.datatype = lambda: [None for x in range(index + 1)] # type: ignore[operator] # noqa: E501 + else: + self.datatype = dict + self.onebased = onebased + + def _fget_default(self, err: Optional[BaseException] = None) -> _T: + if self.default == self._NO_DEFAULT_ARGUMENT: + raise AttributeError(self.attr_name) from err + else: + return self.default + + def fget(self, __instance: Any) -> _T: + attr_name = self.attr_name + column_value = getattr(__instance, attr_name) + if column_value is None: + return self._fget_default() + try: + value = column_value[self.index] + except (KeyError, IndexError) as err: + return self._fget_default(err) + else: + return value # type: ignore[no-any-return] + + def fset(self, instance: Any, value: _T) -> None: + attr_name = self.attr_name + column_value = getattr(instance, attr_name, None) + if column_value is None: + column_value = self.datatype() + setattr(instance, attr_name, column_value) + column_value[self.index] = value + setattr(instance, attr_name, column_value) + if attr_name in inspect(instance).mapper.attrs: + flag_modified(instance, attr_name) + + def fdel(self, instance: Any) -> None: + attr_name = self.attr_name + column_value = getattr(instance, attr_name) + if column_value is None: + raise AttributeError(self.attr_name) + try: + del column_value[self.index] + except KeyError as err: + raise AttributeError(self.attr_name) from err + else: + setattr(instance, attr_name, column_value) + flag_modified(instance, attr_name) + + def expr( + self, model: Any + ) -> Union[_HasClauseElement[_T], SQLColumnExpression[_T]]: + column = getattr(model, self.attr_name) + index = self.index + if self.onebased: + index += 1 # type: ignore[operator] + return column[index] # type: ignore[no-any-return] diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/instrumentation.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..57be0a43ecf632e99ec5bba54558f41a238a0e55 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/instrumentation.py @@ -0,0 +1,450 @@ +# ext/instrumentation.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + +"""Extensible class instrumentation. + +The :mod:`sqlalchemy.ext.instrumentation` package provides for alternate +systems of class instrumentation within the ORM. Class instrumentation +refers to how the ORM places attributes on the class which maintain +data and track changes to that data, as well as event hooks installed +on the class. + +.. note:: + The extension package is provided for the benefit of integration + with other object management packages, which already perform + their own instrumentation. It is not intended for general use. + +For examples of how the instrumentation extension is used, +see the example :ref:`examples_instrumentation`. + +""" +import weakref + +from .. import util +from ..orm import attributes +from ..orm import base as orm_base +from ..orm import collections +from ..orm import exc as orm_exc +from ..orm import instrumentation as orm_instrumentation +from ..orm import util as orm_util +from ..orm.instrumentation import _default_dict_getter +from ..orm.instrumentation import _default_manager_getter +from ..orm.instrumentation import _default_opt_manager_getter +from ..orm.instrumentation import _default_state_getter +from ..orm.instrumentation import ClassManager +from ..orm.instrumentation import InstrumentationFactory + + +INSTRUMENTATION_MANAGER = "__sa_instrumentation_manager__" +"""Attribute, elects custom instrumentation when present on a mapped class. + +Allows a class to specify a slightly or wildly different technique for +tracking changes made to mapped attributes and collections. + +Only one instrumentation implementation is allowed in a given object +inheritance hierarchy. + +The value of this attribute must be a callable and will be passed a class +object. The callable must return one of: + + - An instance of an :class:`.InstrumentationManager` or subclass + - An object implementing all or some of InstrumentationManager (TODO) + - A dictionary of callables, implementing all or some of the above (TODO) + - An instance of a :class:`.ClassManager` or subclass + +This attribute is consulted by SQLAlchemy instrumentation +resolution, once the :mod:`sqlalchemy.ext.instrumentation` module +has been imported. If custom finders are installed in the global +instrumentation_finders list, they may or may not choose to honor this +attribute. + +""" + + +def find_native_user_instrumentation_hook(cls): + """Find user-specified instrumentation management for a class.""" + return getattr(cls, INSTRUMENTATION_MANAGER, None) + + +instrumentation_finders = [find_native_user_instrumentation_hook] +"""An extensible sequence of callables which return instrumentation +implementations + +When a class is registered, each callable will be passed a class object. +If None is returned, the +next finder in the sequence is consulted. Otherwise the return must be an +instrumentation factory that follows the same guidelines as +sqlalchemy.ext.instrumentation.INSTRUMENTATION_MANAGER. + +By default, the only finder is find_native_user_instrumentation_hook, which +searches for INSTRUMENTATION_MANAGER. If all finders return None, standard +ClassManager instrumentation is used. + +""" + + +class ExtendedInstrumentationRegistry(InstrumentationFactory): + """Extends :class:`.InstrumentationFactory` with additional + bookkeeping, to accommodate multiple types of + class managers. + + """ + + _manager_finders = weakref.WeakKeyDictionary() + _state_finders = weakref.WeakKeyDictionary() + _dict_finders = weakref.WeakKeyDictionary() + _extended = False + + def _locate_extended_factory(self, class_): + for finder in instrumentation_finders: + factory = finder(class_) + if factory is not None: + manager = self._extended_class_manager(class_, factory) + return manager, factory + else: + return None, None + + def _check_conflicts(self, class_, factory): + existing_factories = self._collect_management_factories_for( + class_ + ).difference([factory]) + if existing_factories: + raise TypeError( + "multiple instrumentation implementations specified " + "in %s inheritance hierarchy: %r" + % (class_.__name__, list(existing_factories)) + ) + + def _extended_class_manager(self, class_, factory): + manager = factory(class_) + if not isinstance(manager, ClassManager): + manager = _ClassInstrumentationAdapter(class_, manager) + + if factory != ClassManager and not self._extended: + # somebody invoked a custom ClassManager. + # reinstall global "getter" functions with the more + # expensive ones. + self._extended = True + _install_instrumented_lookups() + + self._manager_finders[class_] = manager.manager_getter() + self._state_finders[class_] = manager.state_getter() + self._dict_finders[class_] = manager.dict_getter() + return manager + + def _collect_management_factories_for(self, cls): + """Return a collection of factories in play or specified for a + hierarchy. + + Traverses the entire inheritance graph of a cls and returns a + collection of instrumentation factories for those classes. Factories + are extracted from active ClassManagers, if available, otherwise + instrumentation_finders is consulted. + + """ + hierarchy = util.class_hierarchy(cls) + factories = set() + for member in hierarchy: + manager = self.opt_manager_of_class(member) + if manager is not None: + factories.add(manager.factory) + else: + for finder in instrumentation_finders: + factory = finder(member) + if factory is not None: + break + else: + factory = None + factories.add(factory) + factories.discard(None) + return factories + + def unregister(self, class_): + super().unregister(class_) + if class_ in self._manager_finders: + del self._manager_finders[class_] + del self._state_finders[class_] + del self._dict_finders[class_] + + def opt_manager_of_class(self, cls): + try: + finder = self._manager_finders.get( + cls, _default_opt_manager_getter + ) + except TypeError: + # due to weakref lookup on invalid object + return None + else: + return finder(cls) + + def manager_of_class(self, cls): + try: + finder = self._manager_finders.get(cls, _default_manager_getter) + except TypeError: + # due to weakref lookup on invalid object + raise orm_exc.UnmappedClassError( + cls, f"Can't locate an instrumentation manager for class {cls}" + ) + else: + manager = finder(cls) + if manager is None: + raise orm_exc.UnmappedClassError( + cls, + f"Can't locate an instrumentation manager for class {cls}", + ) + return manager + + def state_of(self, instance): + if instance is None: + raise AttributeError("None has no persistent state.") + return self._state_finders.get( + instance.__class__, _default_state_getter + )(instance) + + def dict_of(self, instance): + if instance is None: + raise AttributeError("None has no persistent state.") + return self._dict_finders.get( + instance.__class__, _default_dict_getter + )(instance) + + +orm_instrumentation._instrumentation_factory = _instrumentation_factory = ( + ExtendedInstrumentationRegistry() +) +orm_instrumentation.instrumentation_finders = instrumentation_finders + + +class InstrumentationManager: + """User-defined class instrumentation extension. + + :class:`.InstrumentationManager` can be subclassed in order + to change + how class instrumentation proceeds. This class exists for + the purposes of integration with other object management + frameworks which would like to entirely modify the + instrumentation methodology of the ORM, and is not intended + for regular usage. For interception of class instrumentation + events, see :class:`.InstrumentationEvents`. + + The API for this class should be considered as semi-stable, + and may change slightly with new releases. + + """ + + # r4361 added a mandatory (cls) constructor to this interface. + # given that, perhaps class_ should be dropped from all of these + # signatures. + + def __init__(self, class_): + pass + + def manage(self, class_, manager): + setattr(class_, "_default_class_manager", manager) + + def unregister(self, class_, manager): + delattr(class_, "_default_class_manager") + + def manager_getter(self, class_): + def get(cls): + return cls._default_class_manager + + return get + + def instrument_attribute(self, class_, key, inst): + pass + + def post_configure_attribute(self, class_, key, inst): + pass + + def install_descriptor(self, class_, key, inst): + setattr(class_, key, inst) + + def uninstall_descriptor(self, class_, key): + delattr(class_, key) + + def install_member(self, class_, key, implementation): + setattr(class_, key, implementation) + + def uninstall_member(self, class_, key): + delattr(class_, key) + + def instrument_collection_class(self, class_, key, collection_class): + return collections.prepare_instrumentation(collection_class) + + def get_instance_dict(self, class_, instance): + return instance.__dict__ + + def initialize_instance_dict(self, class_, instance): + pass + + def install_state(self, class_, instance, state): + setattr(instance, "_default_state", state) + + def remove_state(self, class_, instance): + delattr(instance, "_default_state") + + def state_getter(self, class_): + return lambda instance: getattr(instance, "_default_state") + + def dict_getter(self, class_): + return lambda inst: self.get_instance_dict(class_, inst) + + +class _ClassInstrumentationAdapter(ClassManager): + """Adapts a user-defined InstrumentationManager to a ClassManager.""" + + def __init__(self, class_, override): + self._adapted = override + self._get_state = self._adapted.state_getter(class_) + self._get_dict = self._adapted.dict_getter(class_) + + ClassManager.__init__(self, class_) + + def manage(self): + self._adapted.manage(self.class_, self) + + def unregister(self): + self._adapted.unregister(self.class_, self) + + def manager_getter(self): + return self._adapted.manager_getter(self.class_) + + def instrument_attribute(self, key, inst, propagated=False): + ClassManager.instrument_attribute(self, key, inst, propagated) + if not propagated: + self._adapted.instrument_attribute(self.class_, key, inst) + + def post_configure_attribute(self, key): + super().post_configure_attribute(key) + self._adapted.post_configure_attribute(self.class_, key, self[key]) + + def install_descriptor(self, key, inst): + self._adapted.install_descriptor(self.class_, key, inst) + + def uninstall_descriptor(self, key): + self._adapted.uninstall_descriptor(self.class_, key) + + def install_member(self, key, implementation): + self._adapted.install_member(self.class_, key, implementation) + + def uninstall_member(self, key): + self._adapted.uninstall_member(self.class_, key) + + def instrument_collection_class(self, key, collection_class): + return self._adapted.instrument_collection_class( + self.class_, key, collection_class + ) + + def initialize_collection(self, key, state, factory): + delegate = getattr(self._adapted, "initialize_collection", None) + if delegate: + return delegate(key, state, factory) + else: + return ClassManager.initialize_collection( + self, key, state, factory + ) + + def new_instance(self, state=None): + instance = self.class_.__new__(self.class_) + self.setup_instance(instance, state) + return instance + + def _new_state_if_none(self, instance): + """Install a default InstanceState if none is present. + + A private convenience method used by the __init__ decorator. + """ + if self.has_state(instance): + return False + else: + return self.setup_instance(instance) + + def setup_instance(self, instance, state=None): + self._adapted.initialize_instance_dict(self.class_, instance) + + if state is None: + state = self._state_constructor(instance, self) + + # the given instance is assumed to have no state + self._adapted.install_state(self.class_, instance, state) + return state + + def teardown_instance(self, instance): + self._adapted.remove_state(self.class_, instance) + + def has_state(self, instance): + try: + self._get_state(instance) + except orm_exc.NO_STATE: + return False + else: + return True + + def state_getter(self): + return self._get_state + + def dict_getter(self): + return self._get_dict + + +def _install_instrumented_lookups(): + """Replace global class/object management functions + with ExtendedInstrumentationRegistry implementations, which + allow multiple types of class managers to be present, + at the cost of performance. + + This function is called only by ExtendedInstrumentationRegistry + and unit tests specific to this behavior. + + The _reinstall_default_lookups() function can be called + after this one to re-establish the default functions. + + """ + _install_lookups( + dict( + instance_state=_instrumentation_factory.state_of, + instance_dict=_instrumentation_factory.dict_of, + manager_of_class=_instrumentation_factory.manager_of_class, + opt_manager_of_class=_instrumentation_factory.opt_manager_of_class, + ) + ) + + +def _reinstall_default_lookups(): + """Restore simplified lookups.""" + _install_lookups( + dict( + instance_state=_default_state_getter, + instance_dict=_default_dict_getter, + manager_of_class=_default_manager_getter, + opt_manager_of_class=_default_opt_manager_getter, + ) + ) + _instrumentation_factory._extended = False + + +def _install_lookups(lookups): + global instance_state, instance_dict + global manager_of_class, opt_manager_of_class + instance_state = lookups["instance_state"] + instance_dict = lookups["instance_dict"] + manager_of_class = lookups["manager_of_class"] + opt_manager_of_class = lookups["opt_manager_of_class"] + orm_base.instance_state = attributes.instance_state = ( + orm_instrumentation.instance_state + ) = instance_state + orm_base.instance_dict = attributes.instance_dict = ( + orm_instrumentation.instance_dict + ) = instance_dict + orm_base.manager_of_class = attributes.manager_of_class = ( + orm_instrumentation.manager_of_class + ) = manager_of_class + orm_base.opt_manager_of_class = orm_util.opt_manager_of_class = ( + attributes.opt_manager_of_class + ) = orm_instrumentation.opt_manager_of_class = opt_manager_of_class diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/mutable.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/mutable.py new file mode 100644 index 0000000000000000000000000000000000000000..f3dde792fb7dd7572468eb80be306ce690f189e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/mutable.py @@ -0,0 +1,1085 @@ +# ext/mutable.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +r"""Provide support for tracking of in-place changes to scalar values, +which are propagated into ORM change events on owning parent objects. + +.. _mutable_scalars: + +Establishing Mutability on Scalar Column Values +=============================================== + +A typical example of a "mutable" structure is a Python dictionary. +Following the example introduced in :ref:`types_toplevel`, we +begin with a custom type that marshals Python dictionaries into +JSON strings before being persisted:: + + from sqlalchemy.types import TypeDecorator, VARCHAR + import json + + + class JSONEncodedDict(TypeDecorator): + "Represents an immutable structure as a json-encoded string." + + impl = VARCHAR + + def process_bind_param(self, value, dialect): + if value is not None: + value = json.dumps(value) + return value + + def process_result_value(self, value, dialect): + if value is not None: + value = json.loads(value) + return value + +The usage of ``json`` is only for the purposes of example. The +:mod:`sqlalchemy.ext.mutable` extension can be used +with any type whose target Python type may be mutable, including +:class:`.PickleType`, :class:`_postgresql.ARRAY`, etc. + +When using the :mod:`sqlalchemy.ext.mutable` extension, the value itself +tracks all parents which reference it. Below, we illustrate a simple +version of the :class:`.MutableDict` dictionary object, which applies +the :class:`.Mutable` mixin to a plain Python dictionary:: + + from sqlalchemy.ext.mutable import Mutable + + + class MutableDict(Mutable, dict): + @classmethod + def coerce(cls, key, value): + "Convert plain dictionaries to MutableDict." + + if not isinstance(value, MutableDict): + if isinstance(value, dict): + return MutableDict(value) + + # this call will raise ValueError + return Mutable.coerce(key, value) + else: + return value + + def __setitem__(self, key, value): + "Detect dictionary set events and emit change events." + + dict.__setitem__(self, key, value) + self.changed() + + def __delitem__(self, key): + "Detect dictionary del events and emit change events." + + dict.__delitem__(self, key) + self.changed() + +The above dictionary class takes the approach of subclassing the Python +built-in ``dict`` to produce a dict +subclass which routes all mutation events through ``__setitem__``. There are +variants on this approach, such as subclassing ``UserDict.UserDict`` or +``collections.MutableMapping``; the part that's important to this example is +that the :meth:`.Mutable.changed` method is called whenever an in-place +change to the datastructure takes place. + +We also redefine the :meth:`.Mutable.coerce` method which will be used to +convert any values that are not instances of ``MutableDict``, such +as the plain dictionaries returned by the ``json`` module, into the +appropriate type. Defining this method is optional; we could just as well +created our ``JSONEncodedDict`` such that it always returns an instance +of ``MutableDict``, and additionally ensured that all calling code +uses ``MutableDict`` explicitly. When :meth:`.Mutable.coerce` is not +overridden, any values applied to a parent object which are not instances +of the mutable type will raise a ``ValueError``. + +Our new ``MutableDict`` type offers a class method +:meth:`~.Mutable.as_mutable` which we can use within column metadata +to associate with types. This method grabs the given type object or +class and associates a listener that will detect all future mappings +of this type, applying event listening instrumentation to the mapped +attribute. Such as, with classical table metadata:: + + from sqlalchemy import Table, Column, Integer + + my_data = Table( + "my_data", + metadata, + Column("id", Integer, primary_key=True), + Column("data", MutableDict.as_mutable(JSONEncodedDict)), + ) + +Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict`` +(if the type object was not an instance already), which will intercept any +attributes which are mapped against this type. Below we establish a simple +mapping against the ``my_data`` table:: + + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + + + class Base(DeclarativeBase): + pass + + + class MyDataClass(Base): + __tablename__ = "my_data" + id: Mapped[int] = mapped_column(primary_key=True) + data: Mapped[dict[str, str]] = mapped_column( + MutableDict.as_mutable(JSONEncodedDict) + ) + +The ``MyDataClass.data`` member will now be notified of in place changes +to its value. + +Any in-place changes to the ``MyDataClass.data`` member +will flag the attribute as "dirty" on the parent object:: + + >>> from sqlalchemy.orm import Session + + >>> sess = Session(some_engine) + >>> m1 = MyDataClass(data={"value1": "foo"}) + >>> sess.add(m1) + >>> sess.commit() + + >>> m1.data["value1"] = "bar" + >>> assert m1 in sess.dirty + True + +The ``MutableDict`` can be associated with all future instances +of ``JSONEncodedDict`` in one step, using +:meth:`~.Mutable.associate_with`. This is similar to +:meth:`~.Mutable.as_mutable` except it will intercept all occurrences +of ``MutableDict`` in all mappings unconditionally, without +the need to declare it individually:: + + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + + MutableDict.associate_with(JSONEncodedDict) + + + class Base(DeclarativeBase): + pass + + + class MyDataClass(Base): + __tablename__ = "my_data" + id: Mapped[int] = mapped_column(primary_key=True) + data: Mapped[dict[str, str]] = mapped_column(JSONEncodedDict) + +Supporting Pickling +-------------------- + +The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the +placement of a ``weakref.WeakKeyDictionary`` upon the value object, which +stores a mapping of parent mapped objects keyed to the attribute name under +which they are associated with this value. ``WeakKeyDictionary`` objects are +not picklable, due to the fact that they contain weakrefs and function +callbacks. In our case, this is a good thing, since if this dictionary were +picklable, it could lead to an excessively large pickle size for our value +objects that are pickled by themselves outside of the context of the parent. +The developer responsibility here is only to provide a ``__getstate__`` method +that excludes the :meth:`~MutableBase._parents` collection from the pickle +stream:: + + class MyMutableType(Mutable): + def __getstate__(self): + d = self.__dict__.copy() + d.pop("_parents", None) + return d + +With our dictionary example, we need to return the contents of the dict itself +(and also restore them on __setstate__):: + + class MutableDict(Mutable, dict): + # .... + + def __getstate__(self): + return dict(self) + + def __setstate__(self, state): + self.update(state) + +In the case that our mutable value object is pickled as it is attached to one +or more parent objects that are also part of the pickle, the :class:`.Mutable` +mixin will re-establish the :attr:`.Mutable._parents` collection on each value +object as the owning parents themselves are unpickled. + +Receiving Events +---------------- + +The :meth:`.AttributeEvents.modified` event handler may be used to receive +an event when a mutable scalar emits a change event. This event handler +is called when the :func:`.attributes.flag_modified` function is called +from within the mutable extension:: + + from sqlalchemy.orm import DeclarativeBase + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_column + from sqlalchemy import event + + + class Base(DeclarativeBase): + pass + + + class MyDataClass(Base): + __tablename__ = "my_data" + id: Mapped[int] = mapped_column(primary_key=True) + data: Mapped[dict[str, str]] = mapped_column( + MutableDict.as_mutable(JSONEncodedDict) + ) + + + @event.listens_for(MyDataClass.data, "modified") + def modified_json(instance, initiator): + print("json value modified:", instance.data) + +.. _mutable_composites: + +Establishing Mutability on Composites +===================================== + +Composites are a special ORM feature which allow a single scalar attribute to +be assigned an object value which represents information "composed" from one +or more columns from the underlying mapped table. The usual example is that of +a geometric "point", and is introduced in :ref:`mapper_composite`. + +As is the case with :class:`.Mutable`, the user-defined composite class +subclasses :class:`.MutableComposite` as a mixin, and detects and delivers +change events to its parents via the :meth:`.MutableComposite.changed` method. +In the case of a composite class, the detection is usually via the usage of the +special Python method ``__setattr__()``. In the example below, we expand upon the ``Point`` +class introduced in :ref:`mapper_composite` to include +:class:`.MutableComposite` in its bases and to route attribute set events via +``__setattr__`` to the :meth:`.MutableComposite.changed` method:: + + import dataclasses + from sqlalchemy.ext.mutable import MutableComposite + + + @dataclasses.dataclass + class Point(MutableComposite): + x: int + y: int + + def __setattr__(self, key, value): + "Intercept set events" + + # set the attribute + object.__setattr__(self, key, value) + + # alert all parents to the change + self.changed() + +The :class:`.MutableComposite` class makes use of class mapping events to +automatically establish listeners for any usage of :func:`_orm.composite` that +specifies our ``Point`` type. Below, when ``Point`` is mapped to the ``Vertex`` +class, listeners are established which will route change events from ``Point`` +objects to each of the ``Vertex.start`` and ``Vertex.end`` attributes:: + + from sqlalchemy.orm import DeclarativeBase, Mapped + from sqlalchemy.orm import composite, mapped_column + + + class Base(DeclarativeBase): + pass + + + class Vertex(Base): + __tablename__ = "vertices" + + id: Mapped[int] = mapped_column(primary_key=True) + + start: Mapped[Point] = composite( + mapped_column("x1"), mapped_column("y1") + ) + end: Mapped[Point] = composite( + mapped_column("x2"), mapped_column("y2") + ) + + def __repr__(self): + return f"Vertex(start={self.start}, end={self.end})" + +Any in-place changes to the ``Vertex.start`` or ``Vertex.end`` members +will flag the attribute as "dirty" on the parent object: + +.. sourcecode:: python+sql + + >>> from sqlalchemy.orm import Session + >>> sess = Session(engine) + >>> v1 = Vertex(start=Point(3, 4), end=Point(12, 15)) + >>> sess.add(v1) + {sql}>>> sess.flush() + BEGIN (implicit) + INSERT INTO vertices (x1, y1, x2, y2) VALUES (?, ?, ?, ?) + [...] (3, 4, 12, 15) + + {stop}>>> v1.end.x = 8 + >>> assert v1 in sess.dirty + True + {sql}>>> sess.commit() + UPDATE vertices SET x2=? WHERE vertices.id = ? + [...] (8, 1) + COMMIT + +Coercing Mutable Composites +--------------------------- + +The :meth:`.MutableBase.coerce` method is also supported on composite types. +In the case of :class:`.MutableComposite`, the :meth:`.MutableBase.coerce` +method is only called for attribute set operations, not load operations. +Overriding the :meth:`.MutableBase.coerce` method is essentially equivalent +to using a :func:`.validates` validation routine for all attributes which +make use of the custom composite type:: + + @dataclasses.dataclass + class Point(MutableComposite): + # other Point methods + # ... + + def coerce(cls, key, value): + if isinstance(value, tuple): + value = Point(*value) + elif not isinstance(value, Point): + raise ValueError("tuple or Point expected") + return value + +Supporting Pickling +-------------------- + +As is the case with :class:`.Mutable`, the :class:`.MutableComposite` helper +class uses a ``weakref.WeakKeyDictionary`` available via the +:meth:`MutableBase._parents` attribute which isn't picklable. If we need to +pickle instances of ``Point`` or its owning class ``Vertex``, we at least need +to define a ``__getstate__`` that doesn't include the ``_parents`` dictionary. +Below we define both a ``__getstate__`` and a ``__setstate__`` that package up +the minimal form of our ``Point`` class:: + + @dataclasses.dataclass + class Point(MutableComposite): + # ... + + def __getstate__(self): + return self.x, self.y + + def __setstate__(self, state): + self.x, self.y = state + +As with :class:`.Mutable`, the :class:`.MutableComposite` augments the +pickling process of the parent's object-relational state so that the +:meth:`MutableBase._parents` collection is restored to all ``Point`` objects. + +""" # noqa: E501 + +from __future__ import annotations + +from collections import defaultdict +from typing import AbstractSet +from typing import Any +from typing import Dict +from typing import Iterable +from typing import List +from typing import Optional +from typing import overload +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref +from weakref import WeakKeyDictionary + +from .. import event +from .. import inspect +from .. import types +from ..orm import Mapper +from ..orm._typing import _ExternalEntityType +from ..orm._typing import _O +from ..orm._typing import _T +from ..orm.attributes import AttributeEventToken +from ..orm.attributes import flag_modified +from ..orm.attributes import InstrumentedAttribute +from ..orm.attributes import QueryableAttribute +from ..orm.context import QueryContext +from ..orm.decl_api import DeclarativeAttributeIntercept +from ..orm.state import InstanceState +from ..orm.unitofwork import UOWTransaction +from ..sql._typing import _TypeEngineArgument +from ..sql.base import SchemaEventTarget +from ..sql.schema import Column +from ..sql.type_api import TypeEngine +from ..util import memoized_property +from ..util.typing import SupportsIndex + +_KT = TypeVar("_KT") # Key type. +_VT = TypeVar("_VT") # Value type. + + +class MutableBase: + """Common base class to :class:`.Mutable` + and :class:`.MutableComposite`. + + """ + + @memoized_property + def _parents(self) -> WeakKeyDictionary[Any, Any]: + """Dictionary of parent object's :class:`.InstanceState`->attribute + name on the parent. + + This attribute is a so-called "memoized" property. It initializes + itself with a new ``weakref.WeakKeyDictionary`` the first time + it is accessed, returning the same object upon subsequent access. + + .. versionchanged:: 1.4 the :class:`.InstanceState` is now used + as the key in the weak dictionary rather than the instance + itself. + + """ + + return weakref.WeakKeyDictionary() + + @classmethod + def coerce(cls, key: str, value: Any) -> Optional[Any]: + """Given a value, coerce it into the target type. + + Can be overridden by custom subclasses to coerce incoming + data into a particular type. + + By default, raises ``ValueError``. + + This method is called in different scenarios depending on if + the parent class is of type :class:`.Mutable` or of type + :class:`.MutableComposite`. In the case of the former, it is called + for both attribute-set operations as well as during ORM loading + operations. For the latter, it is only called during attribute-set + operations; the mechanics of the :func:`.composite` construct + handle coercion during load operations. + + + :param key: string name of the ORM-mapped attribute being set. + :param value: the incoming value. + :return: the method should return the coerced value, or raise + ``ValueError`` if the coercion cannot be completed. + + """ + if value is None: + return None + msg = "Attribute '%s' does not accept objects of type %s" + raise ValueError(msg % (key, type(value))) + + @classmethod + def _get_listen_keys(cls, attribute: QueryableAttribute[Any]) -> Set[str]: + """Given a descriptor attribute, return a ``set()`` of the attribute + keys which indicate a change in the state of this attribute. + + This is normally just ``set([attribute.key])``, but can be overridden + to provide for additional keys. E.g. a :class:`.MutableComposite` + augments this set with the attribute keys associated with the columns + that comprise the composite value. + + This collection is consulted in the case of intercepting the + :meth:`.InstanceEvents.refresh` and + :meth:`.InstanceEvents.refresh_flush` events, which pass along a list + of attribute names that have been refreshed; the list is compared + against this set to determine if action needs to be taken. + + """ + return {attribute.key} + + @classmethod + def _listen_on_attribute( + cls, + attribute: QueryableAttribute[Any], + coerce: bool, + parent_cls: _ExternalEntityType[Any], + ) -> None: + """Establish this type as a mutation listener for the given + mapped descriptor. + + """ + key = attribute.key + if parent_cls is not attribute.class_: + return + + # rely on "propagate" here + parent_cls = attribute.class_ + + listen_keys = cls._get_listen_keys(attribute) + + def load(state: InstanceState[_O], *args: Any) -> None: + """Listen for objects loaded or refreshed. + + Wrap the target data member's value with + ``Mutable``. + + """ + val = state.dict.get(key, None) + if val is not None: + if coerce: + val = cls.coerce(key, val) + assert val is not None + state.dict[key] = val + val._parents[state] = key + + def load_attrs( + state: InstanceState[_O], + ctx: Union[object, QueryContext, UOWTransaction], + attrs: Iterable[Any], + ) -> None: + if not attrs or listen_keys.intersection(attrs): + load(state) + + def set_( + target: InstanceState[_O], + value: MutableBase | None, + oldvalue: MutableBase | None, + initiator: AttributeEventToken, + ) -> MutableBase | None: + """Listen for set/replace events on the target + data member. + + Establish a weak reference to the parent object + on the incoming value, remove it for the one + outgoing. + + """ + if value is oldvalue: + return value + + if not isinstance(value, cls): + value = cls.coerce(key, value) + if value is not None: + value._parents[target] = key + if isinstance(oldvalue, cls): + oldvalue._parents.pop(inspect(target), None) + return value + + def pickle( + state: InstanceState[_O], state_dict: Dict[str, Any] + ) -> None: + val = state.dict.get(key, None) + if val is not None: + if "ext.mutable.values" not in state_dict: + state_dict["ext.mutable.values"] = defaultdict(list) + state_dict["ext.mutable.values"][key].append(val) + + def unpickle( + state: InstanceState[_O], state_dict: Dict[str, Any] + ) -> None: + if "ext.mutable.values" in state_dict: + collection = state_dict["ext.mutable.values"] + if isinstance(collection, list): + # legacy format + for val in collection: + val._parents[state] = key + else: + for val in state_dict["ext.mutable.values"][key]: + val._parents[state] = key + + event.listen( + parent_cls, + "_sa_event_merge_wo_load", + load, + raw=True, + propagate=True, + ) + + event.listen(parent_cls, "load", load, raw=True, propagate=True) + event.listen( + parent_cls, "refresh", load_attrs, raw=True, propagate=True + ) + event.listen( + parent_cls, "refresh_flush", load_attrs, raw=True, propagate=True + ) + event.listen( + attribute, "set", set_, raw=True, retval=True, propagate=True + ) + event.listen(parent_cls, "pickle", pickle, raw=True, propagate=True) + event.listen( + parent_cls, "unpickle", unpickle, raw=True, propagate=True + ) + + +class Mutable(MutableBase): + """Mixin that defines transparent propagation of change + events to a parent object. + + See the example in :ref:`mutable_scalars` for usage information. + + """ + + def changed(self) -> None: + """Subclasses should call this method whenever change events occur.""" + + for parent, key in self._parents.items(): + flag_modified(parent.obj(), key) + + @classmethod + def associate_with_attribute( + cls, attribute: InstrumentedAttribute[_O] + ) -> None: + """Establish this type as a mutation listener for the given + mapped descriptor. + + """ + cls._listen_on_attribute(attribute, True, attribute.class_) + + @classmethod + def associate_with(cls, sqltype: type) -> None: + """Associate this wrapper with all future mapped columns + of the given type. + + This is a convenience method that calls + ``associate_with_attribute`` automatically. + + .. warning:: + + The listeners established by this method are *global* + to all mappers, and are *not* garbage collected. Only use + :meth:`.associate_with` for types that are permanent to an + application, not with ad-hoc types else this will cause unbounded + growth in memory usage. + + """ + + def listen_for_type(mapper: Mapper[_O], class_: type) -> None: + if mapper.non_primary: + return + for prop in mapper.column_attrs: + if isinstance(prop.columns[0].type, sqltype): + cls.associate_with_attribute(getattr(class_, prop.key)) + + event.listen(Mapper, "mapper_configured", listen_for_type) + + @classmethod + def as_mutable(cls, sqltype: _TypeEngineArgument[_T]) -> TypeEngine[_T]: + """Associate a SQL type with this mutable Python type. + + This establishes listeners that will detect ORM mappings against + the given type, adding mutation event trackers to those mappings. + + The type is returned, unconditionally as an instance, so that + :meth:`.as_mutable` can be used inline:: + + Table( + "mytable", + metadata, + Column("id", Integer, primary_key=True), + Column("data", MyMutableType.as_mutable(PickleType)), + ) + + Note that the returned type is always an instance, even if a class + is given, and that only columns which are declared specifically with + that type instance receive additional instrumentation. + + To associate a particular mutable type with all occurrences of a + particular type, use the :meth:`.Mutable.associate_with` classmethod + of the particular :class:`.Mutable` subclass to establish a global + association. + + .. warning:: + + The listeners established by this method are *global* + to all mappers, and are *not* garbage collected. Only use + :meth:`.as_mutable` for types that are permanent to an application, + not with ad-hoc types else this will cause unbounded growth + in memory usage. + + """ + sqltype = types.to_instance(sqltype) + + # a SchemaType will be copied when the Column is copied, + # and we'll lose our ability to link that type back to the original. + # so track our original type w/ columns + if isinstance(sqltype, SchemaEventTarget): + + @event.listens_for(sqltype, "before_parent_attach") + def _add_column_memo( + sqltyp: TypeEngine[Any], + parent: Column[_T], + ) -> None: + parent.info["_ext_mutable_orig_type"] = sqltyp + + schema_event_check = True + else: + schema_event_check = False + + def listen_for_type( + mapper: Mapper[_T], + class_: Union[DeclarativeAttributeIntercept, type], + ) -> None: + if mapper.non_primary: + return + _APPLIED_KEY = "_ext_mutable_listener_applied" + + for prop in mapper.column_attrs: + if ( + # all Mutable types refer to a Column that's mapped, + # since this is the only kind of Core target the ORM can + # "mutate" + isinstance(prop.expression, Column) + and ( + ( + schema_event_check + and prop.expression.info.get( + "_ext_mutable_orig_type" + ) + is sqltype + ) + or prop.expression.type is sqltype + ) + ): + if not prop.expression.info.get(_APPLIED_KEY, False): + prop.expression.info[_APPLIED_KEY] = True + cls.associate_with_attribute(getattr(class_, prop.key)) + + event.listen(Mapper, "mapper_configured", listen_for_type) + + return sqltype + + +class MutableComposite(MutableBase): + """Mixin that defines transparent propagation of change + events on a SQLAlchemy "composite" object to its + owning parent or parents. + + See the example in :ref:`mutable_composites` for usage information. + + """ + + @classmethod + def _get_listen_keys(cls, attribute: QueryableAttribute[_O]) -> Set[str]: + return {attribute.key}.union(attribute.property._attribute_keys) + + def changed(self) -> None: + """Subclasses should call this method whenever change events occur.""" + + for parent, key in self._parents.items(): + prop = parent.mapper.get_property(key) + for value, attr_name in zip( + prop._composite_values_from_instance(self), + prop._attribute_keys, + ): + setattr(parent.obj(), attr_name, value) + + +def _setup_composite_listener() -> None: + def _listen_for_type(mapper: Mapper[_T], class_: type) -> None: + for prop in mapper.iterate_properties: + if ( + hasattr(prop, "composite_class") + and isinstance(prop.composite_class, type) + and issubclass(prop.composite_class, MutableComposite) + ): + prop.composite_class._listen_on_attribute( + getattr(class_, prop.key), False, class_ + ) + + if not event.contains(Mapper, "mapper_configured", _listen_for_type): + event.listen(Mapper, "mapper_configured", _listen_for_type) + + +_setup_composite_listener() + + +class MutableDict(Mutable, Dict[_KT, _VT]): + """A dictionary type that implements :class:`.Mutable`. + + The :class:`.MutableDict` object implements a dictionary that will + emit change events to the underlying mapping when the contents of + the dictionary are altered, including when values are added or removed. + + Note that :class:`.MutableDict` does **not** apply mutable tracking to the + *values themselves* inside the dictionary. Therefore it is not a sufficient + solution for the use case of tracking deep changes to a *recursive* + dictionary structure, such as a JSON structure. To support this use case, + build a subclass of :class:`.MutableDict` that provides appropriate + coercion to the values placed in the dictionary so that they too are + "mutable", and emit events up to their parent structure. + + .. seealso:: + + :class:`.MutableList` + + :class:`.MutableSet` + + """ + + def __setitem__(self, key: _KT, value: _VT) -> None: + """Detect dictionary set events and emit change events.""" + dict.__setitem__(self, key, value) + self.changed() + + if TYPE_CHECKING: + # from https://github.com/python/mypy/issues/14858 + + @overload + def setdefault( + self: MutableDict[_KT, Optional[_T]], key: _KT, value: None = None + ) -> Optional[_T]: ... + + @overload + def setdefault(self, key: _KT, value: _VT) -> _VT: ... + + def setdefault(self, key: _KT, value: object = None) -> object: ... + + else: + + def setdefault(self, *arg): # noqa: F811 + result = dict.setdefault(self, *arg) + self.changed() + return result + + def __delitem__(self, key: _KT) -> None: + """Detect dictionary del events and emit change events.""" + dict.__delitem__(self, key) + self.changed() + + def update(self, *a: Any, **kw: _VT) -> None: + dict.update(self, *a, **kw) + self.changed() + + if TYPE_CHECKING: + + @overload + def pop(self, __key: _KT) -> _VT: ... + + @overload + def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... + + def pop( + self, __key: _KT, __default: _VT | _T | None = None + ) -> _VT | _T: ... + + else: + + def pop(self, *arg): # noqa: F811 + result = dict.pop(self, *arg) + self.changed() + return result + + def popitem(self) -> Tuple[_KT, _VT]: + result = dict.popitem(self) + self.changed() + return result + + def clear(self) -> None: + dict.clear(self) + self.changed() + + @classmethod + def coerce(cls, key: str, value: Any) -> MutableDict[_KT, _VT] | None: + """Convert plain dictionary to instance of this class.""" + if not isinstance(value, cls): + if isinstance(value, dict): + return cls(value) + return Mutable.coerce(key, value) + else: + return value + + def __getstate__(self) -> Dict[_KT, _VT]: + return dict(self) + + def __setstate__( + self, state: Union[Dict[str, int], Dict[str, str]] + ) -> None: + self.update(state) + + +class MutableList(Mutable, List[_T]): + """A list type that implements :class:`.Mutable`. + + The :class:`.MutableList` object implements a list that will + emit change events to the underlying mapping when the contents of + the list are altered, including when values are added or removed. + + Note that :class:`.MutableList` does **not** apply mutable tracking to the + *values themselves* inside the list. Therefore it is not a sufficient + solution for the use case of tracking deep changes to a *recursive* + mutable structure, such as a JSON structure. To support this use case, + build a subclass of :class:`.MutableList` that provides appropriate + coercion to the values placed in the dictionary so that they too are + "mutable", and emit events up to their parent structure. + + .. seealso:: + + :class:`.MutableDict` + + :class:`.MutableSet` + + """ + + def __reduce_ex__( + self, proto: SupportsIndex + ) -> Tuple[type, Tuple[List[int]]]: + return (self.__class__, (list(self),)) + + # needed for backwards compatibility with + # older pickles + def __setstate__(self, state: Iterable[_T]) -> None: + self[:] = state + + def __setitem__( + self, index: SupportsIndex | slice, value: _T | Iterable[_T] + ) -> None: + """Detect list set events and emit change events.""" + list.__setitem__(self, index, value) + self.changed() + + def __delitem__(self, index: SupportsIndex | slice) -> None: + """Detect list del events and emit change events.""" + list.__delitem__(self, index) + self.changed() + + def pop(self, *arg: SupportsIndex) -> _T: + result = list.pop(self, *arg) + self.changed() + return result + + def append(self, x: _T) -> None: + list.append(self, x) + self.changed() + + def extend(self, x: Iterable[_T]) -> None: + list.extend(self, x) + self.changed() + + def __iadd__(self, x: Iterable[_T]) -> MutableList[_T]: # type: ignore[override,misc] # noqa: E501 + self.extend(x) + return self + + def insert(self, i: SupportsIndex, x: _T) -> None: + list.insert(self, i, x) + self.changed() + + def remove(self, i: _T) -> None: + list.remove(self, i) + self.changed() + + def clear(self) -> None: + list.clear(self) + self.changed() + + def sort(self, **kw: Any) -> None: + list.sort(self, **kw) + self.changed() + + def reverse(self) -> None: + list.reverse(self) + self.changed() + + @classmethod + def coerce( + cls, key: str, value: MutableList[_T] | _T + ) -> Optional[MutableList[_T]]: + """Convert plain list to instance of this class.""" + if not isinstance(value, cls): + if isinstance(value, list): + return cls(value) + return Mutable.coerce(key, value) + else: + return value + + +class MutableSet(Mutable, Set[_T]): + """A set type that implements :class:`.Mutable`. + + The :class:`.MutableSet` object implements a set that will + emit change events to the underlying mapping when the contents of + the set are altered, including when values are added or removed. + + Note that :class:`.MutableSet` does **not** apply mutable tracking to the + *values themselves* inside the set. Therefore it is not a sufficient + solution for the use case of tracking deep changes to a *recursive* + mutable structure. To support this use case, + build a subclass of :class:`.MutableSet` that provides appropriate + coercion to the values placed in the dictionary so that they too are + "mutable", and emit events up to their parent structure. + + .. seealso:: + + :class:`.MutableDict` + + :class:`.MutableList` + + + """ + + def update(self, *arg: Iterable[_T]) -> None: + set.update(self, *arg) + self.changed() + + def intersection_update(self, *arg: Iterable[Any]) -> None: + set.intersection_update(self, *arg) + self.changed() + + def difference_update(self, *arg: Iterable[Any]) -> None: + set.difference_update(self, *arg) + self.changed() + + def symmetric_difference_update(self, *arg: Iterable[_T]) -> None: + set.symmetric_difference_update(self, *arg) + self.changed() + + def __ior__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501 + self.update(other) + return self + + def __iand__(self, other: AbstractSet[object]) -> MutableSet[_T]: + self.intersection_update(other) + return self + + def __ixor__(self, other: AbstractSet[_T]) -> MutableSet[_T]: # type: ignore[override,misc] # noqa: E501 + self.symmetric_difference_update(other) + return self + + def __isub__(self, other: AbstractSet[object]) -> MutableSet[_T]: # type: ignore[misc,unused-ignore] # noqa: E501 + self.difference_update(other) + return self + + def add(self, elem: _T) -> None: + set.add(self, elem) + self.changed() + + def remove(self, elem: _T) -> None: + set.remove(self, elem) + self.changed() + + def discard(self, elem: _T) -> None: # type: ignore[override,unused-ignore] # noqa: E501 + set.discard(self, elem) + self.changed() + + def pop(self, *arg: Any) -> _T: + result = set.pop(self, *arg) + self.changed() + return result + + def clear(self) -> None: + set.clear(self) + self.changed() + + @classmethod + def coerce(cls, index: str, value: Any) -> Optional[MutableSet[_T]]: + """Convert plain set to instance of this class.""" + if not isinstance(value, cls): + if isinstance(value, set): + return cls(value) + return Mutable.coerce(index, value) + else: + return value + + def __getstate__(self) -> Set[_T]: + return set(self) + + def __setstate__(self, state: Iterable[_T]) -> None: + self.update(state) + + def __reduce_ex__( + self, proto: SupportsIndex + ) -> Tuple[type, Tuple[List[int]]]: + return (self.__class__, (list(self),)) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/orderinglist.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/orderinglist.py new file mode 100644 index 0000000000000000000000000000000000000000..a4532cbb8b9e3594516421f0821282c7fc6b49b4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/orderinglist.py @@ -0,0 +1,439 @@ +# ext/orderinglist.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""A custom list that manages index/position information for contained +elements. + +:author: Jason Kirtland + +``orderinglist`` is a helper for mutable ordered relationships. It will +intercept list operations performed on a :func:`_orm.relationship`-managed +collection and +automatically synchronize changes in list position onto a target scalar +attribute. + +Example: A ``slide`` table, where each row refers to zero or more entries +in a related ``bullet`` table. The bullets within a slide are +displayed in order based on the value of the ``position`` column in the +``bullet`` table. As entries are reordered in memory, the value of the +``position`` attribute should be updated to reflect the new sort order:: + + + Base = declarative_base() + + + class Slide(Base): + __tablename__ = "slide" + + id = Column(Integer, primary_key=True) + name = Column(String) + + bullets = relationship("Bullet", order_by="Bullet.position") + + + class Bullet(Base): + __tablename__ = "bullet" + id = Column(Integer, primary_key=True) + slide_id = Column(Integer, ForeignKey("slide.id")) + position = Column(Integer) + text = Column(String) + +The standard relationship mapping will produce a list-like attribute on each +``Slide`` containing all related ``Bullet`` objects, +but coping with changes in ordering is not handled automatically. +When appending a ``Bullet`` into ``Slide.bullets``, the ``Bullet.position`` +attribute will remain unset until manually assigned. When the ``Bullet`` +is inserted into the middle of the list, the following ``Bullet`` objects +will also need to be renumbered. + +The :class:`.OrderingList` object automates this task, managing the +``position`` attribute on all ``Bullet`` objects in the collection. It is +constructed using the :func:`.ordering_list` factory:: + + from sqlalchemy.ext.orderinglist import ordering_list + + Base = declarative_base() + + + class Slide(Base): + __tablename__ = "slide" + + id = Column(Integer, primary_key=True) + name = Column(String) + + bullets = relationship( + "Bullet", + order_by="Bullet.position", + collection_class=ordering_list("position"), + ) + + + class Bullet(Base): + __tablename__ = "bullet" + id = Column(Integer, primary_key=True) + slide_id = Column(Integer, ForeignKey("slide.id")) + position = Column(Integer) + text = Column(String) + +With the above mapping the ``Bullet.position`` attribute is managed:: + + s = Slide() + s.bullets.append(Bullet()) + s.bullets.append(Bullet()) + s.bullets[1].position + >>> 1 + s.bullets.insert(1, Bullet()) + s.bullets[2].position + >>> 2 + +The :class:`.OrderingList` construct only works with **changes** to a +collection, and not the initial load from the database, and requires that the +list be sorted when loaded. Therefore, be sure to specify ``order_by`` on the +:func:`_orm.relationship` against the target ordering attribute, so that the +ordering is correct when first loaded. + +.. warning:: + + :class:`.OrderingList` only provides limited functionality when a primary + key column or unique column is the target of the sort. Operations + that are unsupported or are problematic include: + + * two entries must trade values. This is not supported directly in the + case of a primary key or unique constraint because it means at least + one row would need to be temporarily removed first, or changed to + a third, neutral value while the switch occurs. + + * an entry must be deleted in order to make room for a new entry. + SQLAlchemy's unit of work performs all INSERTs before DELETEs within a + single flush. In the case of a primary key, it will trade + an INSERT/DELETE of the same primary key for an UPDATE statement in order + to lessen the impact of this limitation, however this does not take place + for a UNIQUE column. + A future feature will allow the "DELETE before INSERT" behavior to be + possible, alleviating this limitation, though this feature will require + explicit configuration at the mapper level for sets of columns that + are to be handled in this way. + +:func:`.ordering_list` takes the name of the related object's ordering +attribute as an argument. By default, the zero-based integer index of the +object's position in the :func:`.ordering_list` is synchronized with the +ordering attribute: index 0 will get position 0, index 1 position 1, etc. To +start numbering at 1 or some other integer, provide ``count_from=1``. + + +""" +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import List +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Type +from typing import TypeVar +from typing import Union + +from ..orm.collections import collection +from ..orm.collections import collection_adapter +from ..util.typing import SupportsIndex + +_T = TypeVar("_T") +OrderingFunc = Callable[[int, Sequence[_T]], object] + + +__all__ = ["ordering_list"] + + +def ordering_list( + attr: str, + count_from: Optional[int] = None, + ordering_func: Optional[OrderingFunc[_T]] = None, + reorder_on_append: bool = False, +) -> Callable[[], OrderingList[_T]]: + """Prepares an :class:`OrderingList` factory for use in mapper definitions. + + Returns an object suitable for use as an argument to a Mapper + relationship's ``collection_class`` option. e.g.:: + + from sqlalchemy.ext.orderinglist import ordering_list + + + class Slide(Base): + __tablename__ = "slide" + + id = Column(Integer, primary_key=True) + name = Column(String) + + bullets = relationship( + "Bullet", + order_by="Bullet.position", + collection_class=ordering_list("position"), + ) + + :param attr: + Name of the mapped attribute to use for storage and retrieval of + ordering information + + :param count_from: + Set up an integer-based ordering, starting at ``count_from``. For + example, ``ordering_list('pos', count_from=1)`` would create a 1-based + list in SQL, storing the value in the 'pos' column. Ignored if + ``ordering_func`` is supplied. + + Additional arguments are passed to the :class:`.OrderingList` constructor. + + """ + + kw = _unsugar_count_from( + count_from=count_from, + ordering_func=ordering_func, + reorder_on_append=reorder_on_append, + ) + return lambda: OrderingList(attr, **kw) + + +# Ordering utility functions + + +def count_from_0(index: int, collection: object) -> int: + """Numbering function: consecutive integers starting at 0.""" + + return index + + +def count_from_1(index: int, collection: object) -> int: + """Numbering function: consecutive integers starting at 1.""" + + return index + 1 + + +def count_from_n_factory(start: int) -> OrderingFunc[Any]: + """Numbering function: consecutive integers starting at arbitrary start.""" + + def f(index: int, collection: object) -> int: + return index + start + + try: + f.__name__ = "count_from_%i" % start + except TypeError: + pass + return f + + +def _unsugar_count_from(**kw: Any) -> Dict[str, Any]: + """Builds counting functions from keyword arguments. + + Keyword argument filter, prepares a simple ``ordering_func`` from a + ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged. + """ + + count_from = kw.pop("count_from", None) + if kw.get("ordering_func", None) is None and count_from is not None: + if count_from == 0: + kw["ordering_func"] = count_from_0 + elif count_from == 1: + kw["ordering_func"] = count_from_1 + else: + kw["ordering_func"] = count_from_n_factory(count_from) + return kw + + +class OrderingList(List[_T]): + """A custom list that manages position information for its children. + + The :class:`.OrderingList` object is normally set up using the + :func:`.ordering_list` factory function, used in conjunction with + the :func:`_orm.relationship` function. + + """ + + ordering_attr: str + ordering_func: OrderingFunc[_T] + reorder_on_append: bool + + def __init__( + self, + ordering_attr: str, + ordering_func: Optional[OrderingFunc[_T]] = None, + reorder_on_append: bool = False, + ): + """A custom list that manages position information for its children. + + ``OrderingList`` is a ``collection_class`` list implementation that + syncs position in a Python list with a position attribute on the + mapped objects. + + This implementation relies on the list starting in the proper order, + so be **sure** to put an ``order_by`` on your relationship. + + :param ordering_attr: + Name of the attribute that stores the object's order in the + relationship. + + :param ordering_func: Optional. A function that maps the position in + the Python list to a value to store in the + ``ordering_attr``. Values returned are usually (but need not be!) + integers. + + An ``ordering_func`` is called with two positional parameters: the + index of the element in the list, and the list itself. + + If omitted, Python list indexes are used for the attribute values. + Two basic pre-built numbering functions are provided in this module: + ``count_from_0`` and ``count_from_1``. For more exotic examples + like stepped numbering, alphabetical and Fibonacci numbering, see + the unit tests. + + :param reorder_on_append: + Default False. When appending an object with an existing (non-None) + ordering value, that value will be left untouched unless + ``reorder_on_append`` is true. This is an optimization to avoid a + variety of dangerous unexpected database writes. + + SQLAlchemy will add instances to the list via append() when your + object loads. If for some reason the result set from the database + skips a step in the ordering (say, row '1' is missing but you get + '2', '3', and '4'), reorder_on_append=True would immediately + renumber the items to '1', '2', '3'. If you have multiple sessions + making changes, any of whom happen to load this collection even in + passing, all of the sessions would try to "clean up" the numbering + in their commits, possibly causing all but one to fail with a + concurrent modification error. + + Recommend leaving this with the default of False, and just call + ``reorder()`` if you're doing ``append()`` operations with + previously ordered instances or when doing some housekeeping after + manual sql operations. + + """ + self.ordering_attr = ordering_attr + if ordering_func is None: + ordering_func = count_from_0 + self.ordering_func = ordering_func + self.reorder_on_append = reorder_on_append + + # More complex serialization schemes (multi column, e.g.) are possible by + # subclassing and reimplementing these two methods. + def _get_order_value(self, entity: _T) -> Any: + return getattr(entity, self.ordering_attr) + + def _set_order_value(self, entity: _T, value: Any) -> None: + setattr(entity, self.ordering_attr, value) + + def reorder(self) -> None: + """Synchronize ordering for the entire collection. + + Sweeps through the list and ensures that each object has accurate + ordering information set. + + """ + for index, entity in enumerate(self): + self._order_entity(index, entity, True) + + # As of 0.5, _reorder is no longer semi-private + _reorder = reorder + + def _order_entity( + self, index: int, entity: _T, reorder: bool = True + ) -> None: + have = self._get_order_value(entity) + + # Don't disturb existing ordering if reorder is False + if have is not None and not reorder: + return + + should_be = self.ordering_func(index, self) + if have != should_be: + self._set_order_value(entity, should_be) + + def append(self, entity: _T) -> None: + super().append(entity) + self._order_entity(len(self) - 1, entity, self.reorder_on_append) + + def _raw_append(self, entity: _T) -> None: + """Append without any ordering behavior.""" + + super().append(entity) + + _raw_append = collection.adds(1)(_raw_append) + + def insert(self, index: SupportsIndex, entity: _T) -> None: + super().insert(index, entity) + self._reorder() + + def remove(self, entity: _T) -> None: + super().remove(entity) + + adapter = collection_adapter(self) + if adapter and adapter._referenced_by_owner: + self._reorder() + + def pop(self, index: SupportsIndex = -1) -> _T: + entity = super().pop(index) + self._reorder() + return entity + + @overload + def __setitem__(self, index: SupportsIndex, entity: _T) -> None: ... + + @overload + def __setitem__(self, index: slice, entity: Iterable[_T]) -> None: ... + + def __setitem__( + self, + index: Union[SupportsIndex, slice], + entity: Union[_T, Iterable[_T]], + ) -> None: + if isinstance(index, slice): + step = index.step or 1 + start = index.start or 0 + if start < 0: + start += len(self) + stop = index.stop or len(self) + if stop < 0: + stop += len(self) + entities = list(entity) # type: ignore[arg-type] + for i in range(start, stop, step): + self.__setitem__(i, entities[i]) + else: + self._order_entity(int(index), entity, True) # type: ignore[arg-type] # noqa: E501 + super().__setitem__(index, entity) # type: ignore[assignment] + + def __delitem__(self, index: Union[SupportsIndex, slice]) -> None: + super().__delitem__(index) + self._reorder() + + def __reduce__(self) -> Any: + return _reconstitute, (self.__class__, self.__dict__, list(self)) + + for func_name, func in list(locals().items()): + if ( + callable(func) + and func.__name__ == func_name + and not func.__doc__ + and hasattr(list, func_name) + ): + func.__doc__ = getattr(list, func_name).__doc__ + del func_name, func + + +def _reconstitute( + cls: Type[OrderingList[_T]], dict_: Dict[str, Any], items: List[_T] +) -> OrderingList[_T]: + """Reconstitute an :class:`.OrderingList`. + + This is the adjoint to :meth:`.OrderingList.__reduce__`. It is used for + unpickling :class:`.OrderingList` objects. + + """ + obj = cls.__new__(cls) + obj.__dict__.update(dict_) + list.extend(obj, items) + return obj diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/ext/serializer.py b/python/user_packages/Python313/site-packages/sqlalchemy/ext/serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..651edfebe930d04fa3d674cee437cd4d38b3ae19 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/ext/serializer.py @@ -0,0 +1,185 @@ +# ext/serializer.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + +"""Serializer/Deserializer objects for usage with SQLAlchemy query structures, +allowing "contextual" deserialization. + +.. legacy:: + + The serializer extension is **legacy** and should not be used for + new development. + +Any SQLAlchemy query structure, either based on sqlalchemy.sql.* +or sqlalchemy.orm.* can be used. The mappers, Tables, Columns, Session +etc. which are referenced by the structure are not persisted in serialized +form, but are instead re-associated with the query structure +when it is deserialized. + +.. warning:: The serializer extension uses pickle to serialize and + deserialize objects, so the same security consideration mentioned + in the `python documentation + `_ apply. + +Usage is nearly the same as that of the standard Python pickle module:: + + from sqlalchemy.ext.serializer import loads, dumps + + metadata = MetaData(bind=some_engine) + Session = scoped_session(sessionmaker()) + + # ... define mappers + + query = ( + Session.query(MyClass) + .filter(MyClass.somedata == "foo") + .order_by(MyClass.sortkey) + ) + + # pickle the query + serialized = dumps(query) + + # unpickle. Pass in metadata + scoped_session + query2 = loads(serialized, metadata, Session) + + print(query2.all()) + +Similar restrictions as when using raw pickle apply; mapped classes must be +themselves be pickleable, meaning they are importable from a module-level +namespace. + +The serializer module is only appropriate for query structures. It is not +needed for: + +* instances of user-defined classes. These contain no references to engines, + sessions or expression constructs in the typical case and can be serialized + directly. + +* Table metadata that is to be loaded entirely from the serialized structure + (i.e. is not already declared in the application). Regular + pickle.loads()/dumps() can be used to fully dump any ``MetaData`` object, + typically one which was reflected from an existing database at some previous + point in time. The serializer module is specifically for the opposite case, + where the Table metadata is already present in memory. + +""" + +from io import BytesIO +import pickle +import re + +from .. import Column +from .. import Table +from ..engine import Engine +from ..orm import class_mapper +from ..orm.interfaces import MapperProperty +from ..orm.mapper import Mapper +from ..orm.session import Session +from ..util import b64decode +from ..util import b64encode + + +__all__ = ["Serializer", "Deserializer", "dumps", "loads"] + + +class Serializer(pickle.Pickler): + + def persistent_id(self, obj): + # print "serializing:", repr(obj) + if isinstance(obj, Mapper) and not obj.non_primary: + id_ = "mapper:" + b64encode(pickle.dumps(obj.class_)) + elif isinstance(obj, MapperProperty) and not obj.parent.non_primary: + id_ = ( + "mapperprop:" + + b64encode(pickle.dumps(obj.parent.class_)) + + ":" + + obj.key + ) + elif isinstance(obj, Table): + if "parententity" in obj._annotations: + id_ = "mapper_selectable:" + b64encode( + pickle.dumps(obj._annotations["parententity"].class_) + ) + else: + id_ = f"table:{obj.key}" + elif isinstance(obj, Column) and isinstance(obj.table, Table): + id_ = f"column:{obj.table.key}:{obj.key}" + elif isinstance(obj, Session): + id_ = "session:" + elif isinstance(obj, Engine): + id_ = "engine:" + else: + return None + return id_ + + +our_ids = re.compile( + r"(mapperprop|mapper|mapper_selectable|table|column|" + r"session|attribute|engine):(.*)" +) + + +class Deserializer(pickle.Unpickler): + + def __init__(self, file, metadata=None, scoped_session=None, engine=None): + super().__init__(file) + self.metadata = metadata + self.scoped_session = scoped_session + self.engine = engine + + def get_engine(self): + if self.engine: + return self.engine + elif self.scoped_session and self.scoped_session().bind: + return self.scoped_session().bind + else: + return None + + def persistent_load(self, id_): + m = our_ids.match(str(id_)) + if not m: + return None + else: + type_, args = m.group(1, 2) + if type_ == "attribute": + key, clsarg = args.split(":") + cls = pickle.loads(b64decode(clsarg)) + return getattr(cls, key) + elif type_ == "mapper": + cls = pickle.loads(b64decode(args)) + return class_mapper(cls) + elif type_ == "mapper_selectable": + cls = pickle.loads(b64decode(args)) + return class_mapper(cls).__clause_element__() + elif type_ == "mapperprop": + mapper, keyname = args.split(":") + cls = pickle.loads(b64decode(mapper)) + return class_mapper(cls).attrs[keyname] + elif type_ == "table": + return self.metadata.tables[args] + elif type_ == "column": + table, colname = args.split(":") + return self.metadata.tables[table].c[colname] + elif type_ == "session": + return self.scoped_session() + elif type_ == "engine": + return self.get_engine() + else: + raise Exception("Unknown token: %s" % type_) + + +def dumps(obj, protocol=pickle.HIGHEST_PROTOCOL): + buf = BytesIO() + pickler = Serializer(buf, protocol) + pickler.dump(obj) + return buf.getvalue() + + +def loads(data, metadata=None, scoped_session=None, engine=None): + buf = BytesIO(data) + unpickler = Deserializer(buf, metadata, scoped_session, engine) + return unpickler.load() diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/future/__init__.py b/python/user_packages/Python313/site-packages/sqlalchemy/future/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..550651ffa3a3c4e446987bdb551ad353fcd03f4c --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/future/__init__.py @@ -0,0 +1,16 @@ +# future/__init__.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""2.0 API features. + +this module is legacy as 2.0 APIs are now standard. + +""" +from .engine import Connection as Connection +from .engine import create_engine as create_engine +from .engine import Engine as Engine +from ..sql._selectable_constructors import select as select diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/future/engine.py b/python/user_packages/Python313/site-packages/sqlalchemy/future/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..af574de7156ff3cec535cacb7402ab5ac940bda0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/future/engine.py @@ -0,0 +1,15 @@ +# future/engine.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +"""2.0 API features. + +this module is legacy as 2.0 APIs are now standard. + +""" + +from ..engine import Connection as Connection # noqa: F401 +from ..engine import create_engine as create_engine # noqa: F401 +from ..engine import Engine as Engine # noqa: F401 diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/attributes.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb271e1ec3046d1cd060bab98f7e9cd311b6994 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/attributes.py @@ -0,0 +1,2845 @@ +# orm/attributes.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: allow-untyped-defs, allow-untyped-calls + +"""Defines instrumentation for class attributes and their interaction +with instances. + +This module is usually not directly visible to user applications, but +defines a large part of the ORM's interactivity. + + +""" + +from __future__ import annotations + +import dataclasses +import operator +from typing import Any +from typing import Callable +from typing import cast +from typing import ClassVar +from typing import Dict +from typing import Iterable +from typing import List +from typing import NamedTuple +from typing import Optional +from typing import overload +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import collections +from . import exc as orm_exc +from . import interfaces +from ._typing import insp_is_aliased_class +from .base import _DeclarativeMapped +from .base import ATTR_EMPTY +from .base import ATTR_WAS_SET +from .base import CALLABLES_OK +from .base import DEFERRED_HISTORY_LOAD +from .base import INCLUDE_PENDING_MUTATIONS # noqa +from .base import INIT_OK +from .base import instance_dict as instance_dict +from .base import instance_state as instance_state +from .base import instance_str +from .base import LOAD_AGAINST_COMMITTED +from .base import LoaderCallableStatus +from .base import manager_of_class as manager_of_class +from .base import Mapped as Mapped # noqa +from .base import NEVER_SET # noqa +from .base import NO_AUTOFLUSH +from .base import NO_CHANGE # noqa +from .base import NO_KEY +from .base import NO_RAISE +from .base import NO_VALUE +from .base import NON_PERSISTENT_OK # noqa +from .base import opt_manager_of_class as opt_manager_of_class +from .base import PASSIVE_CLASS_MISMATCH # noqa +from .base import PASSIVE_NO_FETCH +from .base import PASSIVE_NO_FETCH_RELATED # noqa +from .base import PASSIVE_NO_INITIALIZE +from .base import PASSIVE_NO_RESULT +from .base import PASSIVE_OFF +from .base import PASSIVE_ONLY_PERSISTENT +from .base import PASSIVE_RETURN_NO_VALUE +from .base import PassiveFlag +from .base import RELATED_OBJECT_OK # noqa +from .base import SQL_OK # noqa +from .base import SQLORMExpression +from .base import state_str +from .. import event +from .. import exc +from .. import inspection +from .. import util +from ..event import dispatcher +from ..event import EventTarget +from ..sql import base as sql_base +from ..sql import cache_key +from ..sql import coercions +from ..sql import roles +from ..sql import visitors +from ..sql.cache_key import HasCacheKey +from ..sql.visitors import _TraverseInternalsType +from ..sql.visitors import InternalTraversal +from ..util.typing import Literal +from ..util.typing import Self +from ..util.typing import TypeGuard + +if TYPE_CHECKING: + from ._typing import _EntityType + from ._typing import _ExternalEntityType + from ._typing import _InstanceDict + from ._typing import _InternalEntityType + from ._typing import _LoaderCallable + from ._typing import _O + from .collections import _AdaptedCollectionProtocol + from .collections import CollectionAdapter + from .interfaces import MapperProperty + from .relationships import RelationshipProperty + from .state import InstanceState + from .util import AliasedInsp + from .writeonly import WriteOnlyAttributeImpl + from ..event.base import _Dispatch + from ..sql._typing import _ColumnExpressionArgument + from ..sql._typing import _DMLColumnArgument + from ..sql._typing import _InfoType + from ..sql._typing import _PropagateAttrsType + from ..sql.annotation import _AnnotationDict + from ..sql.elements import ColumnElement + from ..sql.elements import Label + from ..sql.operators import OperatorType + from ..sql.selectable import FromClause + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", bound=Any, covariant=True) + + +_AllPendingType = Sequence[ + Tuple[Optional["InstanceState[Any]"], Optional[object]] +] + + +_UNKNOWN_ATTR_KEY = object() + + +@inspection._self_inspects +class QueryableAttribute( + _DeclarativeMapped[_T_co], + SQLORMExpression[_T_co], + interfaces.InspectionAttr, + interfaces.PropComparator[_T_co], + roles.JoinTargetRole, + roles.OnClauseRole, + sql_base.Immutable, + cache_key.SlotsMemoizedHasCacheKey, + util.MemoizedSlots, + EventTarget, +): + """Base class for :term:`descriptor` objects that intercept + attribute events on behalf of a :class:`.MapperProperty` + object. The actual :class:`.MapperProperty` is accessible + via the :attr:`.QueryableAttribute.property` + attribute. + + + .. seealso:: + + :class:`.InstrumentedAttribute` + + :class:`.MapperProperty` + + :attr:`_orm.Mapper.all_orm_descriptors` + + :attr:`_orm.Mapper.attrs` + """ + + __slots__ = ( + "class_", + "key", + "impl", + "comparator", + "property", + "parent", + "expression", + "_of_type", + "_extra_criteria", + "_slots_dispatch", + "_propagate_attrs", + "_doc", + ) + + is_attribute = True + + dispatch: dispatcher[QueryableAttribute[_T_co]] + + class_: _ExternalEntityType[Any] + key: str + parententity: _InternalEntityType[Any] + impl: AttributeImpl + comparator: interfaces.PropComparator[_T_co] + _of_type: Optional[_InternalEntityType[Any]] + _extra_criteria: Tuple[ColumnElement[bool], ...] + _doc: Optional[str] + + # PropComparator has a __visit_name__ to participate within + # traversals. Disambiguate the attribute vs. a comparator. + __visit_name__ = "orm_instrumented_attribute" + + def __init__( + self, + class_: _ExternalEntityType[_O], + key: str, + parententity: _InternalEntityType[_O], + comparator: interfaces.PropComparator[_T_co], + impl: Optional[AttributeImpl] = None, + of_type: Optional[_InternalEntityType[Any]] = None, + extra_criteria: Tuple[ColumnElement[bool], ...] = (), + ): + self.class_ = class_ + self.key = key + + self._parententity = self.parent = parententity + + # this attribute is non-None after mappers are set up, however in the + # interim class manager setup, there's a check for None to see if it + # needs to be populated, so we assign None here leaving the attribute + # in a temporarily not-type-correct state + self.impl = impl # type: ignore + + assert comparator is not None + self.comparator = comparator + self._of_type = of_type + self._extra_criteria = extra_criteria + self._doc = None + + manager = opt_manager_of_class(class_) + # manager is None in the case of AliasedClass + if manager: + # propagate existing event listeners from + # immediate superclass + for base in manager._bases: + if key in base: + self.dispatch._update(base[key].dispatch) + if base[key].dispatch._active_history: + self.dispatch._active_history = True # type: ignore + + _cache_key_traversal = [ + ("key", visitors.ExtendedInternalTraversal.dp_string), + ("_parententity", visitors.ExtendedInternalTraversal.dp_multi), + ("_of_type", visitors.ExtendedInternalTraversal.dp_multi), + ("_extra_criteria", visitors.InternalTraversal.dp_clauseelement_list), + ] + + def __reduce__(self) -> Any: + # this method is only used in terms of the + # sqlalchemy.ext.serializer extension + return ( + _queryable_attribute_unreduce, + ( + self.key, + self._parententity.mapper.class_, + self._parententity, + self._parententity.entity, + ), + ) + + @property + def _impl_uses_objects(self) -> bool: + return self.impl.uses_objects + + def get_history( + self, instance: Any, passive: PassiveFlag = PASSIVE_OFF + ) -> History: + return self.impl.get_history( + instance_state(instance), instance_dict(instance), passive + ) + + @property + def info(self) -> _InfoType: + """Return the 'info' dictionary for the underlying SQL element. + + The behavior here is as follows: + + * If the attribute is a column-mapped property, i.e. + :class:`.ColumnProperty`, which is mapped directly + to a schema-level :class:`_schema.Column` object, this attribute + will return the :attr:`.SchemaItem.info` dictionary associated + with the core-level :class:`_schema.Column` object. + + * If the attribute is a :class:`.ColumnProperty` but is mapped to + any other kind of SQL expression other than a + :class:`_schema.Column`, + the attribute will refer to the :attr:`.MapperProperty.info` + dictionary associated directly with the :class:`.ColumnProperty`, + assuming the SQL expression itself does not have its own ``.info`` + attribute (which should be the case, unless a user-defined SQL + construct has defined one). + + * If the attribute refers to any other kind of + :class:`.MapperProperty`, including :class:`.Relationship`, + the attribute will refer to the :attr:`.MapperProperty.info` + dictionary associated with that :class:`.MapperProperty`. + + * To access the :attr:`.MapperProperty.info` dictionary of the + :class:`.MapperProperty` unconditionally, including for a + :class:`.ColumnProperty` that's associated directly with a + :class:`_schema.Column`, the attribute can be referred to using + :attr:`.QueryableAttribute.property` attribute, as + ``MyClass.someattribute.property.info``. + + .. seealso:: + + :attr:`.SchemaItem.info` + + :attr:`.MapperProperty.info` + + """ + return self.comparator.info + + parent: _InternalEntityType[Any] + """Return an inspection instance representing the parent. + + This will be either an instance of :class:`_orm.Mapper` + or :class:`.AliasedInsp`, depending upon the nature + of the parent entity which this attribute is associated + with. + + """ + + expression: ColumnElement[_T_co] + """The SQL expression object represented by this + :class:`.QueryableAttribute`. + + This will typically be an instance of a :class:`_sql.ColumnElement` + subclass representing a column expression. + + """ + + def _memoized_attr_expression(self) -> ColumnElement[_T]: + annotations: _AnnotationDict + + # applies only to Proxy() as used by hybrid. + # currently is an exception to typing rather than feeding through + # non-string keys. + # ideally Proxy() would have a separate set of methods to deal + # with this case. + entity_namespace = self._entity_namespace + assert isinstance(entity_namespace, HasCacheKey) + + if self.key is _UNKNOWN_ATTR_KEY: + annotations = {"entity_namespace": entity_namespace} + else: + annotations = { + "proxy_key": self.key, + "proxy_owner": self._parententity, + "entity_namespace": entity_namespace, + } + + ce = self.comparator.__clause_element__() + try: + if TYPE_CHECKING: + assert isinstance(ce, ColumnElement) + anno = ce._annotate + except AttributeError as ae: + raise exc.InvalidRequestError( + 'When interpreting attribute "%s" as a SQL expression, ' + "expected __clause_element__() to return " + "a ClauseElement object, got: %r" % (self, ce) + ) from ae + else: + return anno(annotations) + + def _memoized_attr__propagate_attrs(self) -> _PropagateAttrsType: + # this suits the case in coercions where we don't actually + # call ``__clause_element__()`` but still need to get + # resolved._propagate_attrs. See #6558. + return util.immutabledict( + { + "compile_state_plugin": "orm", + "plugin_subject": self._parentmapper, + } + ) + + @property + def _entity_namespace(self) -> _InternalEntityType[Any]: + return self._parententity + + @property + def _annotations(self) -> _AnnotationDict: + return self.__clause_element__()._annotations + + def __clause_element__(self) -> ColumnElement[_T_co]: + return self.expression + + @property + def _from_objects(self) -> List[FromClause]: + return self.expression._from_objects + + def _bulk_update_tuples( + self, value: Any + ) -> Sequence[Tuple[_DMLColumnArgument, Any]]: + """Return setter tuples for a bulk UPDATE.""" + + return self.comparator._bulk_update_tuples(value) + + def adapt_to_entity(self, adapt_to_entity: AliasedInsp[Any]) -> Self: + assert not self._of_type + return self.__class__( + adapt_to_entity.entity, + self.key, + impl=self.impl, + comparator=self.comparator.adapt_to_entity(adapt_to_entity), + parententity=adapt_to_entity, + ) + + def of_type(self, entity: _EntityType[_T]) -> QueryableAttribute[_T]: + return QueryableAttribute( + self.class_, + self.key, + self._parententity, + impl=self.impl, + comparator=self.comparator.of_type(entity), + of_type=inspection.inspect(entity), + extra_criteria=self._extra_criteria, + ) + + def and_( + self, *clauses: _ColumnExpressionArgument[bool] + ) -> QueryableAttribute[bool]: + if TYPE_CHECKING: + assert isinstance(self.comparator, RelationshipProperty.Comparator) + + exprs = tuple( + coercions.expect(roles.WhereHavingRole, clause) + for clause in util.coerce_generator_arg(clauses) + ) + + return QueryableAttribute( + self.class_, + self.key, + self._parententity, + impl=self.impl, + comparator=self.comparator.and_(*exprs), + of_type=self._of_type, + extra_criteria=self._extra_criteria + exprs, + ) + + def _clone(self, **kw: Any) -> QueryableAttribute[_T]: + return QueryableAttribute( + self.class_, + self.key, + self._parententity, + impl=self.impl, + comparator=self.comparator, + of_type=self._of_type, + extra_criteria=self._extra_criteria, + ) + + def label(self, name: Optional[str]) -> Label[_T_co]: + return self.__clause_element__().label(name) + + def operate( + self, op: OperatorType, *other: Any, **kwargs: Any + ) -> ColumnElement[Any]: + return op(self.comparator, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501 + + def reverse_operate( + self, op: OperatorType, other: Any, **kwargs: Any + ) -> ColumnElement[Any]: + return op(other, self.comparator, **kwargs) # type: ignore[no-any-return] # noqa: E501 + + def hasparent( + self, state: InstanceState[Any], optimistic: bool = False + ) -> bool: + return self.impl.hasparent(state, optimistic=optimistic) is not False + + def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]: + return (self,) + + def __getattr__(self, key: str) -> Any: + try: + return util.MemoizedSlots.__getattr__(self, key) + except AttributeError: + pass + + try: + return getattr(self.comparator, key) + except AttributeError as err: + raise AttributeError( + "Neither %r object nor %r object associated with %s " + "has an attribute %r" + % ( + type(self).__name__, + type(self.comparator).__name__, + self, + key, + ) + ) from err + + def __str__(self) -> str: + return f"{self.class_.__name__}.{self.key}" + + def _memoized_attr_property(self) -> Optional[MapperProperty[Any]]: + return self.comparator.property + + +def _queryable_attribute_unreduce( + key: str, + mapped_class: Type[_O], + parententity: _InternalEntityType[_O], + entity: _ExternalEntityType[Any], +) -> Any: + # this method is only used in terms of the + # sqlalchemy.ext.serializer extension + if insp_is_aliased_class(parententity): + return entity._get_from_serialized(key, mapped_class, parententity) + else: + return getattr(entity, key) + + +class InstrumentedAttribute(QueryableAttribute[_T_co]): + """Class bound instrumented attribute which adds basic + :term:`descriptor` methods. + + See :class:`.QueryableAttribute` for a description of most features. + + + """ + + __slots__ = () + + inherit_cache = True + """:meta private:""" + + # hack to make __doc__ writeable on instances of + # InstrumentedAttribute, while still keeping classlevel + # __doc__ correct + + @util.rw_hybridproperty + def __doc__(self) -> Optional[str]: + return self._doc + + @__doc__.setter # type: ignore + def __doc__(self, value: Optional[str]) -> None: + self._doc = value + + @__doc__.classlevel # type: ignore + def __doc__(cls) -> Optional[str]: + return super().__doc__ + + def __set__(self, instance: object, value: Any) -> None: + self.impl.set( + instance_state(instance), instance_dict(instance), value, None + ) + + def __delete__(self, instance: object) -> None: + self.impl.delete(instance_state(instance), instance_dict(instance)) + + @overload + def __get__( + self, instance: None, owner: Any + ) -> InstrumentedAttribute[_T_co]: ... + + @overload + def __get__(self, instance: object, owner: Any) -> _T_co: ... + + def __get__( + self, instance: Optional[object], owner: Any + ) -> Union[InstrumentedAttribute[_T_co], _T_co]: + if instance is None: + return self + + dict_ = instance_dict(instance) + if self.impl.supports_population and self.key in dict_: + return dict_[self.key] # type: ignore[no-any-return] + else: + try: + state = instance_state(instance) + except AttributeError as err: + raise orm_exc.UnmappedInstanceError(instance) from err + return self.impl.get(state, dict_) # type: ignore[no-any-return] + + +@dataclasses.dataclass(frozen=True) +class AdHocHasEntityNamespace(HasCacheKey): + _traverse_internals: ClassVar[_TraverseInternalsType] = [ + ("_entity_namespace", InternalTraversal.dp_has_cache_key), + ] + + # py37 compat, no slots=True on dataclass + __slots__ = ("_entity_namespace",) + _entity_namespace: _InternalEntityType[Any] + is_mapper: ClassVar[bool] = False + is_aliased_class: ClassVar[bool] = False + + @property + def entity_namespace(self): + return self._entity_namespace.entity_namespace + + +def create_proxied_attribute( + descriptor: Any, +) -> Callable[..., QueryableAttribute[Any]]: + """Create an QueryableAttribute / user descriptor hybrid. + + Returns a new QueryableAttribute type that delegates descriptor + behavior and getattr() to the given descriptor. + """ + + # TODO: can move this to descriptor_props if the need for this + # function is removed from ext/hybrid.py + + class Proxy(QueryableAttribute[_T_co]): + """Presents the :class:`.QueryableAttribute` interface as a + proxy on top of a Python descriptor / :class:`.PropComparator` + combination. + + """ + + _extra_criteria = () + + # the attribute error catches inside of __getattr__ basically create a + # singularity if you try putting slots on this too + # __slots__ = ("descriptor", "original_property", "_comparator") + + def __init__( + self, + class_: _ExternalEntityType[Any], + key: str, + descriptor: Any, + comparator: interfaces.PropComparator[_T_co], + adapt_to_entity: Optional[AliasedInsp[Any]] = None, + doc: Optional[str] = None, + original_property: Optional[QueryableAttribute[_T_co]] = None, + ): + self.class_ = class_ + self.key = key + self.descriptor = descriptor + self.original_property = original_property + self._comparator = comparator + self._adapt_to_entity = adapt_to_entity + self._doc = self.__doc__ = doc + + @property + def _parententity(self): # type: ignore[override] + return inspection.inspect(self.class_, raiseerr=False) + + @property + def parent(self): # type: ignore[override] + return inspection.inspect(self.class_, raiseerr=False) + + _is_internal_proxy = True + + _cache_key_traversal = [ + ("key", visitors.ExtendedInternalTraversal.dp_string), + ("_parententity", visitors.ExtendedInternalTraversal.dp_multi), + ] + + def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]: + prop = self.original_property + if prop is None: + return () + else: + return prop._column_strategy_attrs() + + @property + def _impl_uses_objects(self): + return ( + self.original_property is not None + and getattr(self.class_, self.key).impl.uses_objects + ) + + @property + def _entity_namespace(self): + if hasattr(self._comparator, "_parententity"): + return self._comparator._parententity + else: + # used by hybrid attributes which try to remain + # agnostic of any ORM concepts like mappers + return AdHocHasEntityNamespace(self._parententity) + + @property + def property(self): + return self.comparator.property + + @util.memoized_property + def comparator(self): + if callable(self._comparator): + self._comparator = self._comparator() + if self._adapt_to_entity: + self._comparator = self._comparator.adapt_to_entity( + self._adapt_to_entity + ) + return self._comparator + + def adapt_to_entity(self, adapt_to_entity): + return self.__class__( + adapt_to_entity.entity, + self.key, + self.descriptor, + self._comparator, + adapt_to_entity, + ) + + def _clone(self, **kw): + return self.__class__( + self.class_, + self.key, + self.descriptor, + self._comparator, + adapt_to_entity=self._adapt_to_entity, + original_property=self.original_property, + ) + + def __get__(self, instance, owner): + retval = self.descriptor.__get__(instance, owner) + # detect if this is a plain Python @property, which just returns + # itself for class level access. If so, then return us. + # Otherwise, return the object returned by the descriptor. + if retval is self.descriptor and instance is None: + return self + else: + return retval + + def __str__(self) -> str: + return f"{self.class_.__name__}.{self.key}" + + def __getattr__(self, attribute): + """Delegate __getattr__ to the original descriptor and/or + comparator.""" + + # this is unfortunately very complicated, and is easily prone + # to recursion overflows when implementations of related + # __getattr__ schemes are changed + + try: + return util.MemoizedSlots.__getattr__(self, attribute) + except AttributeError: + pass + + try: + return getattr(descriptor, attribute) + except AttributeError as err: + if attribute == "comparator": + raise AttributeError("comparator") from err + try: + # comparator itself might be unreachable + comparator = self.comparator + except AttributeError as err2: + raise AttributeError( + "Neither %r object nor unconfigured comparator " + "object associated with %s has an attribute %r" + % (type(descriptor).__name__, self, attribute) + ) from err2 + else: + try: + return getattr(comparator, attribute) + except AttributeError as err3: + raise AttributeError( + "Neither %r object nor %r object " + "associated with %s has an attribute %r" + % ( + type(descriptor).__name__, + type(comparator).__name__, + self, + attribute, + ) + ) from err3 + + Proxy.__name__ = type(descriptor).__name__ + "Proxy" + + util.monkeypatch_proxied_specials( + Proxy, type(descriptor), name="descriptor", from_instance=descriptor + ) + return Proxy + + +OP_REMOVE = util.symbol("REMOVE") +OP_APPEND = util.symbol("APPEND") +OP_REPLACE = util.symbol("REPLACE") +OP_BULK_REPLACE = util.symbol("BULK_REPLACE") +OP_MODIFIED = util.symbol("MODIFIED") + + +class AttributeEventToken: + """A token propagated throughout the course of a chain of attribute + events. + + Serves as an indicator of the source of the event and also provides + a means of controlling propagation across a chain of attribute + operations. + + The :class:`.Event` object is sent as the ``initiator`` argument + when dealing with events such as :meth:`.AttributeEvents.append`, + :meth:`.AttributeEvents.set`, + and :meth:`.AttributeEvents.remove`. + + The :class:`.Event` object is currently interpreted by the backref + event handlers, and is used to control the propagation of operations + across two mutually-dependent attributes. + + .. versionchanged:: 2.0 Changed the name from ``AttributeEvent`` + to ``AttributeEventToken``. + + :attribute impl: The :class:`.AttributeImpl` which is the current event + initiator. + + :attribute op: The symbol :attr:`.OP_APPEND`, :attr:`.OP_REMOVE`, + :attr:`.OP_REPLACE`, or :attr:`.OP_BULK_REPLACE`, indicating the + source operation. + + """ + + __slots__ = "impl", "op", "parent_token" + + def __init__(self, attribute_impl: AttributeImpl, op: util.symbol): + self.impl = attribute_impl + self.op = op + self.parent_token = self.impl.parent_token + + def __eq__(self, other): + return ( + isinstance(other, AttributeEventToken) + and other.impl is self.impl + and other.op == self.op + ) + + @property + def key(self): + return self.impl.key + + def hasparent(self, state): + return self.impl.hasparent(state) + + +AttributeEvent = AttributeEventToken # legacy +Event = AttributeEventToken # legacy + + +class AttributeImpl: + """internal implementation for instrumented attributes.""" + + collection: bool + default_accepts_scalar_loader: bool + uses_objects: bool + supports_population: bool + dynamic: bool + + _is_has_collection_adapter = False + + _replace_token: AttributeEventToken + _remove_token: AttributeEventToken + _append_token: AttributeEventToken + + def __init__( + self, + class_: _ExternalEntityType[_O], + key: str, + callable_: Optional[_LoaderCallable], + dispatch: _Dispatch[QueryableAttribute[Any]], + trackparent: bool = False, + compare_function: Optional[Callable[..., bool]] = None, + active_history: bool = False, + parent_token: Optional[AttributeEventToken] = None, + load_on_unexpire: bool = True, + send_modified_events: bool = True, + accepts_scalar_loader: Optional[bool] = None, + **kwargs: Any, + ): + r"""Construct an AttributeImpl. + + :param \class_: associated class + + :param key: string name of the attribute + + :param \callable_: + optional function which generates a callable based on a parent + instance, which produces the "default" values for a scalar or + collection attribute when it's first accessed, if not present + already. + + :param trackparent: + if True, attempt to track if an instance has a parent attached + to it via this attribute. + + :param compare_function: + a function that compares two values which are normally + assignable to this attribute. + + :param active_history: + indicates that get_history() should always return the "old" value, + even if it means executing a lazy callable upon attribute change. + + :param parent_token: + Usually references the MapperProperty, used as a key for + the hasparent() function to identify an "owning" attribute. + Allows multiple AttributeImpls to all match a single + owner attribute. + + :param load_on_unexpire: + if False, don't include this attribute in a load-on-expired + operation, i.e. the "expired_attribute_loader" process. + The attribute can still be in the "expired" list and be + considered to be "expired". Previously, this flag was called + "expire_missing" and is only used by a deferred column + attribute. + + :param send_modified_events: + if False, the InstanceState._modified_event method will have no + effect; this means the attribute will never show up as changed in a + history entry. + + """ + self.class_ = class_ + self.key = key + self.callable_ = callable_ + self.dispatch = dispatch + self.trackparent = trackparent + self.parent_token = parent_token or self + self.send_modified_events = send_modified_events + if compare_function is None: + self.is_equal = operator.eq + else: + self.is_equal = compare_function + + if accepts_scalar_loader is not None: + self.accepts_scalar_loader = accepts_scalar_loader + else: + self.accepts_scalar_loader = self.default_accepts_scalar_loader + + _deferred_history = kwargs.pop("_deferred_history", False) + self._deferred_history = _deferred_history + + if active_history: + self.dispatch._active_history = True + + self.load_on_unexpire = load_on_unexpire + self._modified_token = AttributeEventToken(self, OP_MODIFIED) + + __slots__ = ( + "class_", + "key", + "callable_", + "dispatch", + "trackparent", + "parent_token", + "send_modified_events", + "is_equal", + "load_on_unexpire", + "_modified_token", + "accepts_scalar_loader", + "_deferred_history", + ) + + def __str__(self) -> str: + return f"{self.class_.__name__}.{self.key}" + + def _get_active_history(self): + """Backwards compat for impl.active_history""" + + return self.dispatch._active_history + + def _set_active_history(self, value): + self.dispatch._active_history = value + + active_history = property(_get_active_history, _set_active_history) + + def hasparent( + self, state: InstanceState[Any], optimistic: bool = False + ) -> bool: + """Return the boolean value of a `hasparent` flag attached to + the given state. + + The `optimistic` flag determines what the default return value + should be if no `hasparent` flag can be located. + + As this function is used to determine if an instance is an + *orphan*, instances that were loaded from storage should be + assumed to not be orphans, until a True/False value for this + flag is set. + + An instance attribute that is loaded by a callable function + will also not have a `hasparent` flag. + + """ + msg = "This AttributeImpl is not configured to track parents." + assert self.trackparent, msg + + return ( + state.parents.get(id(self.parent_token), optimistic) is not False + ) + + def sethasparent( + self, + state: InstanceState[Any], + parent_state: InstanceState[Any], + value: bool, + ) -> None: + """Set a boolean flag on the given item corresponding to + whether or not it is attached to a parent object via the + attribute represented by this ``InstrumentedAttribute``. + + """ + msg = "This AttributeImpl is not configured to track parents." + assert self.trackparent, msg + + id_ = id(self.parent_token) + if value: + state.parents[id_] = parent_state + else: + if id_ in state.parents: + last_parent = state.parents[id_] + + if ( + last_parent is not False + and last_parent.key != parent_state.key + ): + if last_parent.obj() is None: + raise orm_exc.StaleDataError( + "Removing state %s from parent " + "state %s along attribute '%s', " + "but the parent record " + "has gone stale, can't be sure this " + "is the most recent parent." + % ( + state_str(state), + state_str(parent_state), + self.key, + ) + ) + + return + + state.parents[id_] = False + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_OFF, + ) -> History: + raise NotImplementedError() + + def get_all_pending( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_NO_INITIALIZE, + ) -> _AllPendingType: + """Return a list of tuples of (state, obj) + for all objects in this attribute's current state + + history. + + Only applies to object-based attributes. + + This is an inlining of existing functionality + which roughly corresponds to: + + get_state_history( + state, + key, + passive=PASSIVE_NO_INITIALIZE).sum() + + """ + raise NotImplementedError() + + def _default_value( + self, state: InstanceState[Any], dict_: _InstanceDict + ) -> Any: + """Produce an empty value for an uninitialized scalar attribute.""" + + assert self.key not in dict_, ( + "_default_value should only be invoked for an " + "uninitialized or expired attribute" + ) + + value = None + for fn in self.dispatch.init_scalar: + ret = fn(state, value, dict_) + if ret is not ATTR_EMPTY: + value = ret + + return value + + def get( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_OFF, + ) -> Any: + """Retrieve a value from the given object. + If a callable is assembled on this object's attribute, and + passive is False, the callable will be executed and the + resulting value will be set as the new value for this attribute. + """ + if self.key in dict_: + return dict_[self.key] + else: + # if history present, don't load + key = self.key + if ( + key not in state.committed_state + or state.committed_state[key] is NO_VALUE + ): + if not passive & CALLABLES_OK: + return PASSIVE_NO_RESULT + + value = self._fire_loader_callables(state, key, passive) + + if value is PASSIVE_NO_RESULT or value is NO_VALUE: + return value + elif value is ATTR_WAS_SET: + try: + return dict_[key] + except KeyError as err: + # TODO: no test coverage here. + raise KeyError( + "Deferred loader for attribute " + "%r failed to populate " + "correctly" % key + ) from err + elif value is not ATTR_EMPTY: + return self.set_committed_value(state, dict_, value) + + if not passive & INIT_OK: + return NO_VALUE + else: + return self._default_value(state, dict_) + + def _fire_loader_callables( + self, state: InstanceState[Any], key: str, passive: PassiveFlag + ) -> Any: + if ( + self.accepts_scalar_loader + and self.load_on_unexpire + and key in state.expired_attributes + ): + return state._load_expired(state, passive) + elif key in state.callables: + callable_ = state.callables[key] + return callable_(state, passive) + elif self.callable_: + return self.callable_(state, passive) + else: + return ATTR_EMPTY + + def append( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + self.set(state, dict_, value, initiator, passive=passive) + + def remove( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + self.set( + state, dict_, None, initiator, passive=passive, check_old=value + ) + + def pop( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + self.set( + state, + dict_, + None, + initiator, + passive=passive, + check_old=value, + pop=True, + ) + + def set( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken] = None, + passive: PassiveFlag = PASSIVE_OFF, + check_old: Any = None, + pop: bool = False, + ) -> None: + raise NotImplementedError() + + def delete(self, state: InstanceState[Any], dict_: _InstanceDict) -> None: + raise NotImplementedError() + + def get_committed_value( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_OFF, + ) -> Any: + """return the unchanged value of this attribute""" + + if self.key in state.committed_state: + value = state.committed_state[self.key] + if value is NO_VALUE: + return None + else: + return value + else: + return self.get(state, dict_, passive=passive) + + def set_committed_value(self, state, dict_, value): + """set an attribute value on the given instance and 'commit' it.""" + + dict_[self.key] = value + state._commit(dict_, [self.key]) + return value + + +class ScalarAttributeImpl(AttributeImpl): + """represents a scalar value-holding InstrumentedAttribute.""" + + default_accepts_scalar_loader = True + uses_objects = False + supports_population = True + collection = False + dynamic = False + + __slots__ = "_replace_token", "_append_token", "_remove_token" + + def __init__(self, *arg, **kw): + super().__init__(*arg, **kw) + self._replace_token = self._append_token = AttributeEventToken( + self, OP_REPLACE + ) + self._remove_token = AttributeEventToken(self, OP_REMOVE) + + def delete(self, state: InstanceState[Any], dict_: _InstanceDict) -> None: + if self.dispatch._active_history: + old = self.get(state, dict_, PASSIVE_RETURN_NO_VALUE) + else: + old = dict_.get(self.key, NO_VALUE) + + if self.dispatch.remove: + self.fire_remove_event(state, dict_, old, self._remove_token) + state._modified_event(dict_, self, old) + + existing = dict_.pop(self.key, NO_VALUE) + if ( + existing is NO_VALUE + and old is NO_VALUE + and not state.expired + and self.key not in state.expired_attributes + ): + raise AttributeError("%s object does not have a value" % self) + + def get_history( + self, + state: InstanceState[Any], + dict_: Dict[str, Any], + passive: PassiveFlag = PASSIVE_OFF, + ) -> History: + if self.key in dict_: + return History.from_scalar_attribute(self, state, dict_[self.key]) + elif self.key in state.committed_state: + return History.from_scalar_attribute(self, state, NO_VALUE) + else: + if passive & INIT_OK: + passive ^= INIT_OK + current = self.get(state, dict_, passive=passive) + if current is PASSIVE_NO_RESULT: + return HISTORY_BLANK + else: + return History.from_scalar_attribute(self, state, current) + + def set( + self, + state: InstanceState[Any], + dict_: Dict[str, Any], + value: Any, + initiator: Optional[AttributeEventToken] = None, + passive: PassiveFlag = PASSIVE_OFF, + check_old: Optional[object] = None, + pop: bool = False, + ) -> None: + if self.dispatch._active_history: + old = self.get(state, dict_, PASSIVE_RETURN_NO_VALUE) + else: + old = dict_.get(self.key, NO_VALUE) + + if self.dispatch.set: + value = self.fire_replace_event( + state, dict_, value, old, initiator + ) + state._modified_event(dict_, self, old) + dict_[self.key] = value + + def fire_replace_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: _T, + previous: Any, + initiator: Optional[AttributeEventToken], + ) -> _T: + for fn in self.dispatch.set: + value = fn( + state, value, previous, initiator or self._replace_token + ) + return value + + def fire_remove_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + ) -> None: + for fn in self.dispatch.remove: + fn(state, value, initiator or self._remove_token) + + +class ScalarObjectAttributeImpl(ScalarAttributeImpl): + """represents a scalar-holding InstrumentedAttribute, + where the target object is also instrumented. + + Adds events to delete/set operations. + + """ + + default_accepts_scalar_loader = False + uses_objects = True + supports_population = True + collection = False + + __slots__ = () + + def delete(self, state: InstanceState[Any], dict_: _InstanceDict) -> None: + if self.dispatch._active_history: + old = self.get( + state, + dict_, + passive=PASSIVE_ONLY_PERSISTENT + | NO_AUTOFLUSH + | LOAD_AGAINST_COMMITTED, + ) + else: + old = self.get( + state, + dict_, + passive=PASSIVE_NO_FETCH ^ INIT_OK + | LOAD_AGAINST_COMMITTED + | NO_RAISE, + ) + + self.fire_remove_event(state, dict_, old, self._remove_token) + + existing = dict_.pop(self.key, NO_VALUE) + + # if the attribute is expired, we currently have no way to tell + # that an object-attribute was expired vs. not loaded. So + # for this test, we look to see if the object has a DB identity. + if ( + existing is NO_VALUE + and old is not PASSIVE_NO_RESULT + and state.key is None + ): + raise AttributeError("%s object does not have a value" % self) + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_OFF, + ) -> History: + if self.key in dict_: + current = dict_[self.key] + else: + if passive & INIT_OK: + passive ^= INIT_OK + current = self.get(state, dict_, passive=passive) + if current is PASSIVE_NO_RESULT: + return HISTORY_BLANK + + if not self._deferred_history: + return History.from_object_attribute(self, state, current) + else: + original = state.committed_state.get(self.key, _NO_HISTORY) + if original is PASSIVE_NO_RESULT: + loader_passive = passive | ( + PASSIVE_ONLY_PERSISTENT + | NO_AUTOFLUSH + | LOAD_AGAINST_COMMITTED + | NO_RAISE + | DEFERRED_HISTORY_LOAD + ) + original = self._fire_loader_callables( + state, self.key, loader_passive + ) + return History.from_object_attribute( + self, state, current, original=original + ) + + def get_all_pending( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_NO_INITIALIZE, + ) -> _AllPendingType: + if self.key in dict_: + current = dict_[self.key] + elif passive & CALLABLES_OK: + current = self.get(state, dict_, passive=passive) + else: + return [] + + ret: _AllPendingType + + # can't use __hash__(), can't use __eq__() here + if ( + current is not None + and current is not PASSIVE_NO_RESULT + and current is not NO_VALUE + ): + ret = [(instance_state(current), current)] + else: + ret = [(None, None)] + + if self.key in state.committed_state: + original = state.committed_state[self.key] + if ( + original is not None + and original is not PASSIVE_NO_RESULT + and original is not NO_VALUE + and original is not current + ): + ret.append((instance_state(original), original)) + return ret + + def set( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken] = None, + passive: PassiveFlag = PASSIVE_OFF, + check_old: Any = None, + pop: bool = False, + ) -> None: + """Set a value on the given InstanceState.""" + + if self.dispatch._active_history: + old = self.get( + state, + dict_, + passive=PASSIVE_ONLY_PERSISTENT + | NO_AUTOFLUSH + | LOAD_AGAINST_COMMITTED, + ) + else: + old = self.get( + state, + dict_, + passive=PASSIVE_NO_FETCH ^ INIT_OK + | LOAD_AGAINST_COMMITTED + | NO_RAISE, + ) + + if ( + check_old is not None + and old is not PASSIVE_NO_RESULT + and check_old is not old + ): + if pop: + return + else: + raise ValueError( + "Object %s not associated with %s on attribute '%s'" + % (instance_str(check_old), state_str(state), self.key) + ) + + value = self.fire_replace_event(state, dict_, value, old, initiator) + dict_[self.key] = value + + def fire_remove_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + ) -> None: + if self.trackparent and value not in ( + None, + PASSIVE_NO_RESULT, + NO_VALUE, + ): + self.sethasparent(instance_state(value), state, False) + + for fn in self.dispatch.remove: + fn(state, value, initiator or self._remove_token) + + state._modified_event(dict_, self, value) + + def fire_replace_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: _T, + previous: Any, + initiator: Optional[AttributeEventToken], + ) -> _T: + if self.trackparent: + if previous is not value and previous not in ( + None, + PASSIVE_NO_RESULT, + NO_VALUE, + ): + self.sethasparent(instance_state(previous), state, False) + + for fn in self.dispatch.set: + value = fn( + state, value, previous, initiator or self._replace_token + ) + + state._modified_event(dict_, self, previous) + + if self.trackparent: + if value is not None: + self.sethasparent(instance_state(value), state, True) + + return value + + +class HasCollectionAdapter: + __slots__ = () + + collection: bool + _is_has_collection_adapter = True + + def _dispose_previous_collection( + self, + state: InstanceState[Any], + collection: _AdaptedCollectionProtocol, + adapter: CollectionAdapter, + fire_event: bool, + ) -> None: + raise NotImplementedError() + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Literal[None] = ..., + passive: Literal[PassiveFlag.PASSIVE_OFF] = ..., + ) -> CollectionAdapter: ... + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: _AdaptedCollectionProtocol = ..., + passive: PassiveFlag = ..., + ) -> CollectionAdapter: ... + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Optional[_AdaptedCollectionProtocol] = ..., + passive: PassiveFlag = ..., + ) -> Union[ + Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter + ]: ... + + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Optional[_AdaptedCollectionProtocol] = None, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + ) -> Union[ + Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter + ]: + raise NotImplementedError() + + def set( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken] = None, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + check_old: Any = None, + pop: bool = False, + _adapt: bool = True, + ) -> None: + raise NotImplementedError() + + +if TYPE_CHECKING: + + def _is_collection_attribute_impl( + impl: AttributeImpl, + ) -> TypeGuard[CollectionAttributeImpl]: ... + +else: + _is_collection_attribute_impl = operator.attrgetter("collection") + + +class CollectionAttributeImpl(HasCollectionAdapter, AttributeImpl): + """A collection-holding attribute that instruments changes in membership. + + Only handles collections of instrumented objects. + + InstrumentedCollectionAttribute holds an arbitrary, user-specified + container object (defaulting to a list) and brokers access to the + CollectionAdapter, a "view" onto that object that presents consistent bag + semantics to the orm layer independent of the user data implementation. + + """ + + uses_objects = True + collection = True + default_accepts_scalar_loader = False + supports_population = True + dynamic = False + + _bulk_replace_token: AttributeEventToken + + __slots__ = ( + "copy", + "collection_factory", + "_append_token", + "_remove_token", + "_bulk_replace_token", + "_duck_typed_as", + ) + + def __init__( + self, + class_, + key, + callable_, + dispatch, + typecallable=None, + trackparent=False, + copy_function=None, + compare_function=None, + **kwargs, + ): + super().__init__( + class_, + key, + callable_, + dispatch, + trackparent=trackparent, + compare_function=compare_function, + **kwargs, + ) + + if copy_function is None: + copy_function = self.__copy + self.copy = copy_function + self.collection_factory = typecallable + self._append_token = AttributeEventToken(self, OP_APPEND) + self._remove_token = AttributeEventToken(self, OP_REMOVE) + self._bulk_replace_token = AttributeEventToken(self, OP_BULK_REPLACE) + self._duck_typed_as = util.duck_type_collection( + self.collection_factory() + ) + + if getattr(self.collection_factory, "_sa_linker", None): + + @event.listens_for(self, "init_collection") + def link(target, collection, collection_adapter): + collection._sa_linker(collection_adapter) + + @event.listens_for(self, "dispose_collection") + def unlink(target, collection, collection_adapter): + collection._sa_linker(None) + + def __copy(self, item): + return [y for y in collections.collection_adapter(item)] + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_OFF, + ) -> History: + current = self.get(state, dict_, passive=passive) + + if current is PASSIVE_NO_RESULT: + if ( + passive & PassiveFlag.INCLUDE_PENDING_MUTATIONS + and self.key in state._pending_mutations + ): + pending = state._pending_mutations[self.key] + return pending.merge_with_history(HISTORY_BLANK) + else: + return HISTORY_BLANK + else: + if passive & PassiveFlag.INCLUDE_PENDING_MUTATIONS: + # this collection is loaded / present. should not be any + # pending mutations + assert self.key not in state._pending_mutations + + return History.from_collection(self, state, current) + + def get_all_pending( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PASSIVE_NO_INITIALIZE, + ) -> _AllPendingType: + # NOTE: passive is ignored here at the moment + + if self.key not in dict_: + return [] + + current = dict_[self.key] + current = getattr(current, "_sa_adapter") + + if self.key in state.committed_state: + original = state.committed_state[self.key] + if original is not NO_VALUE: + current_states = [ + ((c is not None) and instance_state(c) or None, c) + for c in current + ] + original_states = [ + ((c is not None) and instance_state(c) or None, c) + for c in original + ] + + current_set = dict(current_states) + original_set = dict(original_states) + + return ( + [ + (s, o) + for s, o in current_states + if s not in original_set + ] + + [(s, o) for s, o in current_states if s in original_set] + + [ + (s, o) + for s, o in original_states + if s not in current_set + ] + ) + + return [(instance_state(o), o) for o in current] + + def fire_append_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: _T, + initiator: Optional[AttributeEventToken], + key: Optional[Any], + ) -> _T: + for fn in self.dispatch.append: + value = fn(state, value, initiator or self._append_token, key=key) + + state._modified_event(dict_, self, NO_VALUE, True) + + if self.trackparent and value is not None: + self.sethasparent(instance_state(value), state, True) + + return value + + def fire_append_wo_mutation_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: _T, + initiator: Optional[AttributeEventToken], + key: Optional[Any], + ) -> _T: + for fn in self.dispatch.append_wo_mutation: + value = fn(state, value, initiator or self._append_token, key=key) + + return value + + def fire_pre_remove_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + initiator: Optional[AttributeEventToken], + key: Optional[Any], + ) -> None: + """A special event used for pop() operations. + + The "remove" event needs to have the item to be removed passed to + it, which in the case of pop from a set, we don't have a way to access + the item before the operation. the event is used for all pop() + operations (even though set.pop is the one where it is really needed). + + """ + state._modified_event(dict_, self, NO_VALUE, True) + + def fire_remove_event( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + key: Optional[Any], + ) -> None: + if self.trackparent and value is not None: + self.sethasparent(instance_state(value), state, False) + + for fn in self.dispatch.remove: + fn(state, value, initiator or self._remove_token, key=key) + + state._modified_event(dict_, self, NO_VALUE, True) + + def delete(self, state: InstanceState[Any], dict_: _InstanceDict) -> None: + if self.key not in dict_: + return + + state._modified_event(dict_, self, NO_VALUE, True) + + collection = self.get_collection(state, state.dict) + collection.clear_with_event() + + # key is always present because we checked above. e.g. + # del is a no-op if collection not present. + del dict_[self.key] + + def _default_value( + self, state: InstanceState[Any], dict_: _InstanceDict + ) -> _AdaptedCollectionProtocol: + """Produce an empty collection for an un-initialized attribute""" + + assert self.key not in dict_, ( + "_default_value should only be invoked for an " + "uninitialized or expired attribute" + ) + + if self.key in state._empty_collections: + return state._empty_collections[self.key] + + adapter, user_data = self._initialize_collection(state) + adapter._set_empty(user_data) + return user_data + + def _initialize_collection( + self, state: InstanceState[Any] + ) -> Tuple[CollectionAdapter, _AdaptedCollectionProtocol]: + adapter, collection = state.manager.initialize_collection( + self.key, state, self.collection_factory + ) + + self.dispatch.init_collection(state, collection, adapter) + + return adapter, collection + + def append( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + collection = self.get_collection( + state, dict_, user_data=None, passive=passive + ) + if collection is PASSIVE_NO_RESULT: + value = self.fire_append_event( + state, dict_, value, initiator, key=NO_KEY + ) + assert ( + self.key not in dict_ + ), "Collection was loaded during event handling." + state._get_pending_mutation(self.key).append(value) + else: + if TYPE_CHECKING: + assert isinstance(collection, CollectionAdapter) + collection.append_with_event(value, initiator) + + def remove( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + collection = self.get_collection( + state, state.dict, user_data=None, passive=passive + ) + if collection is PASSIVE_NO_RESULT: + self.fire_remove_event(state, dict_, value, initiator, key=NO_KEY) + assert ( + self.key not in dict_ + ), "Collection was loaded during event handling." + state._get_pending_mutation(self.key).remove(value) + else: + if TYPE_CHECKING: + assert isinstance(collection, CollectionAdapter) + collection.remove_with_event(value, initiator) + + def pop( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken], + passive: PassiveFlag = PASSIVE_OFF, + ) -> None: + try: + # TODO: better solution here would be to add + # a "popper" role to collections.py to complement + # "remover". + self.remove(state, dict_, value, initiator, passive=passive) + except (ValueError, KeyError, IndexError): + pass + + def set( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + value: Any, + initiator: Optional[AttributeEventToken] = None, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + check_old: Any = None, + pop: bool = False, + _adapt: bool = True, + ) -> None: + iterable = orig_iterable = value + new_keys = None + + # pulling a new collection first so that an adaptation exception does + # not trigger a lazy load of the old collection. + new_collection, user_data = self._initialize_collection(state) + if _adapt: + if new_collection._converter is not None: + iterable = new_collection._converter(iterable) + else: + setting_type = util.duck_type_collection(iterable) + receiving_type = self._duck_typed_as + + if setting_type is not receiving_type: + given = ( + iterable is None + and "None" + or iterable.__class__.__name__ + ) + wanted = self._duck_typed_as.__name__ + raise TypeError( + "Incompatible collection type: %s is not %s-like" + % (given, wanted) + ) + + # If the object is an adapted collection, return the (iterable) + # adapter. + if hasattr(iterable, "_sa_iterator"): + iterable = iterable._sa_iterator() + elif setting_type is dict: + new_keys = list(iterable) + iterable = iterable.values() + else: + iterable = iter(iterable) + elif util.duck_type_collection(iterable) is dict: + new_keys = list(value) + + new_values = list(iterable) + + evt = self._bulk_replace_token + + self.dispatch.bulk_replace(state, new_values, evt, keys=new_keys) + + # propagate NO_RAISE in passive through to the get() for the + # existing object (ticket #8862) + old = self.get( + state, + dict_, + passive=PASSIVE_ONLY_PERSISTENT ^ (passive & PassiveFlag.NO_RAISE), + ) + if old is PASSIVE_NO_RESULT: + old = self._default_value(state, dict_) + elif old is orig_iterable: + # ignore re-assignment of the current collection, as happens + # implicitly with in-place operators (foo.collection |= other) + return + + # place a copy of "old" in state.committed_state + state._modified_event(dict_, self, old, True) + + old_collection = old._sa_adapter + + dict_[self.key] = user_data + + collections.bulk_replace( + new_values, old_collection, new_collection, initiator=evt + ) + + self._dispose_previous_collection(state, old, old_collection, True) + + def _dispose_previous_collection( + self, + state: InstanceState[Any], + collection: _AdaptedCollectionProtocol, + adapter: CollectionAdapter, + fire_event: bool, + ) -> None: + del collection._sa_adapter + + # discarding old collection make sure it is not referenced in empty + # collections. + state._empty_collections.pop(self.key, None) + if fire_event: + self.dispatch.dispose_collection(state, collection, adapter) + + def _invalidate_collection( + self, collection: _AdaptedCollectionProtocol + ) -> None: + adapter = getattr(collection, "_sa_adapter") + adapter.invalidated = True + + def set_committed_value( + self, state: InstanceState[Any], dict_: _InstanceDict, value: Any + ) -> _AdaptedCollectionProtocol: + """Set an attribute value on the given instance and 'commit' it.""" + + collection, user_data = self._initialize_collection(state) + + if value: + collection.append_multiple_without_event(value) + + state.dict[self.key] = user_data + + state._commit(dict_, [self.key]) + + if self.key in state._pending_mutations: + # pending items exist. issue a modified event, + # add/remove new items. + state._modified_event(dict_, self, user_data, True) + + pending = state._pending_mutations.pop(self.key) + added = pending.added_items + removed = pending.deleted_items + for item in added: + collection.append_without_event(item) + for item in removed: + collection.remove_without_event(item) + + return user_data + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Literal[None] = ..., + passive: Literal[PassiveFlag.PASSIVE_OFF] = ..., + ) -> CollectionAdapter: ... + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: _AdaptedCollectionProtocol = ..., + passive: PassiveFlag = ..., + ) -> CollectionAdapter: ... + + @overload + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Optional[_AdaptedCollectionProtocol] = ..., + passive: PassiveFlag = PASSIVE_OFF, + ) -> Union[ + Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter + ]: ... + + def get_collection( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + user_data: Optional[_AdaptedCollectionProtocol] = None, + passive: PassiveFlag = PASSIVE_OFF, + ) -> Union[ + Literal[LoaderCallableStatus.PASSIVE_NO_RESULT], CollectionAdapter + ]: + """Retrieve the CollectionAdapter associated with the given state. + + if user_data is None, retrieves it from the state using normal + "get()" rules, which will fire lazy callables or return the "empty" + collection value. + + """ + if user_data is None: + fetch_user_data = self.get(state, dict_, passive=passive) + if fetch_user_data is LoaderCallableStatus.PASSIVE_NO_RESULT: + return fetch_user_data + else: + user_data = cast("_AdaptedCollectionProtocol", fetch_user_data) + + return user_data._sa_adapter + + +def backref_listeners( + attribute: QueryableAttribute[Any], key: str, uselist: bool +) -> None: + """Apply listeners to synchronize a two-way relationship.""" + + # use easily recognizable names for stack traces. + + # in the sections marked "tokens to test for a recursive loop", + # this is somewhat brittle and very performance-sensitive logic + # that is specific to how we might arrive at each event. a marker + # that can target us directly to arguments being invoked against + # the impl might be simpler, but could interfere with other systems. + + parent_token = attribute.impl.parent_token + parent_impl = attribute.impl + + def _acceptable_key_err(child_state, initiator, child_impl): + raise ValueError( + "Bidirectional attribute conflict detected: " + 'Passing object %s to attribute "%s" ' + 'triggers a modify event on attribute "%s" ' + 'via the backref "%s".' + % ( + state_str(child_state), + initiator.parent_token, + child_impl.parent_token, + attribute.impl.parent_token, + ) + ) + + def emit_backref_from_scalar_set_event( + state, child, oldchild, initiator, **kw + ): + if oldchild is child: + return child + if ( + oldchild is not None + and oldchild is not PASSIVE_NO_RESULT + and oldchild is not NO_VALUE + ): + # With lazy=None, there's no guarantee that the full collection is + # present when updating via a backref. + old_state, old_dict = ( + instance_state(oldchild), + instance_dict(oldchild), + ) + impl = old_state.manager[key].impl + + # tokens to test for a recursive loop. + if not impl.collection and not impl.dynamic: + check_recursive_token = impl._replace_token + else: + check_recursive_token = impl._remove_token + + if initiator is not check_recursive_token: + impl.pop( + old_state, + old_dict, + state.obj(), + parent_impl._append_token, + passive=PASSIVE_NO_FETCH, + ) + + if child is not None: + child_state, child_dict = ( + instance_state(child), + instance_dict(child), + ) + child_impl = child_state.manager[key].impl + + if ( + initiator.parent_token is not parent_token + and initiator.parent_token is not child_impl.parent_token + ): + _acceptable_key_err(state, initiator, child_impl) + + # tokens to test for a recursive loop. + check_append_token = child_impl._append_token + check_bulk_replace_token = ( + child_impl._bulk_replace_token + if _is_collection_attribute_impl(child_impl) + else None + ) + + if ( + initiator is not check_append_token + and initiator is not check_bulk_replace_token + ): + child_impl.append( + child_state, + child_dict, + state.obj(), + initiator, + passive=PASSIVE_NO_FETCH, + ) + return child + + def emit_backref_from_collection_append_event( + state, child, initiator, **kw + ): + if child is None: + return + + child_state, child_dict = instance_state(child), instance_dict(child) + child_impl = child_state.manager[key].impl + + if ( + initiator.parent_token is not parent_token + and initiator.parent_token is not child_impl.parent_token + ): + _acceptable_key_err(state, initiator, child_impl) + + # tokens to test for a recursive loop. + check_append_token = child_impl._append_token + check_bulk_replace_token = ( + child_impl._bulk_replace_token + if _is_collection_attribute_impl(child_impl) + else None + ) + + if ( + initiator is not check_append_token + and initiator is not check_bulk_replace_token + ): + child_impl.append( + child_state, + child_dict, + state.obj(), + initiator, + passive=PASSIVE_NO_FETCH, + ) + return child + + def emit_backref_from_collection_remove_event( + state, child, initiator, **kw + ): + if ( + child is not None + and child is not PASSIVE_NO_RESULT + and child is not NO_VALUE + ): + child_state, child_dict = ( + instance_state(child), + instance_dict(child), + ) + child_impl = child_state.manager[key].impl + + check_replace_token: Optional[AttributeEventToken] + + # tokens to test for a recursive loop. + if not child_impl.collection and not child_impl.dynamic: + check_remove_token = child_impl._remove_token + check_replace_token = child_impl._replace_token + check_for_dupes_on_remove = uselist and not parent_impl.dynamic + else: + check_remove_token = child_impl._remove_token + check_replace_token = ( + child_impl._bulk_replace_token + if _is_collection_attribute_impl(child_impl) + else None + ) + check_for_dupes_on_remove = False + + if ( + initiator is not check_remove_token + and initiator is not check_replace_token + ): + if not check_for_dupes_on_remove or not util.has_dupes( + # when this event is called, the item is usually + # present in the list, except for a pop() operation. + state.dict[parent_impl.key], + child, + ): + child_impl.pop( + child_state, + child_dict, + state.obj(), + initiator, + passive=PASSIVE_NO_FETCH, + ) + + if uselist: + event.listen( + attribute, + "append", + emit_backref_from_collection_append_event, + retval=True, + raw=True, + include_key=True, + ) + else: + event.listen( + attribute, + "set", + emit_backref_from_scalar_set_event, + retval=True, + raw=True, + include_key=True, + ) + # TODO: need coverage in test/orm/ of remove event + event.listen( + attribute, + "remove", + emit_backref_from_collection_remove_event, + retval=True, + raw=True, + include_key=True, + ) + + +_NO_HISTORY = util.symbol("NO_HISTORY") +_NO_STATE_SYMBOLS = frozenset([id(PASSIVE_NO_RESULT), id(NO_VALUE)]) + + +class History(NamedTuple): + """A 3-tuple of added, unchanged and deleted values, + representing the changes which have occurred on an instrumented + attribute. + + The easiest way to get a :class:`.History` object for a particular + attribute on an object is to use the :func:`_sa.inspect` function:: + + from sqlalchemy import inspect + + hist = inspect(myobject).attrs.myattribute.history + + Each tuple member is an iterable sequence: + + * ``added`` - the collection of items added to the attribute (the first + tuple element). + + * ``unchanged`` - the collection of items that have not changed on the + attribute (the second tuple element). + + * ``deleted`` - the collection of items that have been removed from the + attribute (the third tuple element). + + """ + + added: Union[Tuple[()], List[Any]] + unchanged: Union[Tuple[()], List[Any]] + deleted: Union[Tuple[()], List[Any]] + + def __bool__(self) -> bool: + return self != HISTORY_BLANK + + def empty(self) -> bool: + """Return True if this :class:`.History` has no changes + and no existing, unchanged state. + + """ + + return not bool((self.added or self.deleted) or self.unchanged) + + def sum(self) -> Sequence[Any]: + """Return a collection of added + unchanged + deleted.""" + + return ( + (self.added or []) + (self.unchanged or []) + (self.deleted or []) + ) + + def non_deleted(self) -> Sequence[Any]: + """Return a collection of added + unchanged.""" + + return (self.added or []) + (self.unchanged or []) + + def non_added(self) -> Sequence[Any]: + """Return a collection of unchanged + deleted.""" + + return (self.unchanged or []) + (self.deleted or []) + + def has_changes(self) -> bool: + """Return True if this :class:`.History` has changes.""" + + return bool(self.added or self.deleted) + + def _merge(self, added: Iterable[Any], deleted: Iterable[Any]) -> History: + return History( + list(self.added) + list(added), + self.unchanged, + list(self.deleted) + list(deleted), + ) + + def as_state(self) -> History: + return History( + [ + (c is not None) and instance_state(c) or None + for c in self.added + ], + [ + (c is not None) and instance_state(c) or None + for c in self.unchanged + ], + [ + (c is not None) and instance_state(c) or None + for c in self.deleted + ], + ) + + @classmethod + def from_scalar_attribute( + cls, + attribute: ScalarAttributeImpl, + state: InstanceState[Any], + current: Any, + ) -> History: + original = state.committed_state.get(attribute.key, _NO_HISTORY) + + deleted: Union[Tuple[()], List[Any]] + + if original is _NO_HISTORY: + if current is NO_VALUE: + return cls((), (), ()) + else: + return cls((), [current], ()) + # don't let ClauseElement expressions here trip things up + elif ( + current is not NO_VALUE + and attribute.is_equal(current, original) is True + ): + return cls((), [current], ()) + else: + # current convention on native scalars is to not + # include information + # about missing previous value in "deleted", but + # we do include None, which helps in some primary + # key situations + if id(original) in _NO_STATE_SYMBOLS: + deleted = () + # indicate a "del" operation occurred when we don't have + # the previous value as: ([None], (), ()) + if id(current) in _NO_STATE_SYMBOLS: + current = None + else: + deleted = [original] + if current is NO_VALUE: + return cls((), (), deleted) + else: + return cls([current], (), deleted) + + @classmethod + def from_object_attribute( + cls, + attribute: ScalarObjectAttributeImpl, + state: InstanceState[Any], + current: Any, + original: Any = _NO_HISTORY, + ) -> History: + deleted: Union[Tuple[()], List[Any]] + + if original is _NO_HISTORY: + original = state.committed_state.get(attribute.key, _NO_HISTORY) + + if original is _NO_HISTORY: + if current is NO_VALUE: + return cls((), (), ()) + else: + return cls((), [current], ()) + elif current is original and current is not NO_VALUE: + return cls((), [current], ()) + else: + # current convention on related objects is to not + # include information + # about missing previous value in "deleted", and + # to also not include None - the dependency.py rules + # ignore the None in any case. + if id(original) in _NO_STATE_SYMBOLS or original is None: + deleted = () + # indicate a "del" operation occurred when we don't have + # the previous value as: ([None], (), ()) + if id(current) in _NO_STATE_SYMBOLS: + current = None + else: + deleted = [original] + if current is NO_VALUE: + return cls((), (), deleted) + else: + return cls([current], (), deleted) + + @classmethod + def from_collection( + cls, + attribute: CollectionAttributeImpl, + state: InstanceState[Any], + current: Any, + ) -> History: + original = state.committed_state.get(attribute.key, _NO_HISTORY) + if current is NO_VALUE: + return cls((), (), ()) + + current = getattr(current, "_sa_adapter") + if original is NO_VALUE: + return cls(list(current), (), ()) + elif original is _NO_HISTORY: + return cls((), list(current), ()) + else: + current_states = [ + ((c is not None) and instance_state(c) or None, c) + for c in current + ] + original_states = [ + ((c is not None) and instance_state(c) or None, c) + for c in original + ] + + current_set = dict(current_states) + original_set = dict(original_states) + + return cls( + [o for s, o in current_states if s not in original_set], + [o for s, o in current_states if s in original_set], + [o for s, o in original_states if s not in current_set], + ) + + +HISTORY_BLANK = History((), (), ()) + + +def get_history( + obj: object, key: str, passive: PassiveFlag = PASSIVE_OFF +) -> History: + """Return a :class:`.History` record for the given object + and attribute key. + + This is the **pre-flush** history for a given attribute, which is + reset each time the :class:`.Session` flushes changes to the + current database transaction. + + .. note:: + + Prefer to use the :attr:`.AttributeState.history` and + :meth:`.AttributeState.load_history` accessors to retrieve the + :class:`.History` for instance attributes. + + + :param obj: an object whose class is instrumented by the + attributes package. + + :param key: string attribute name. + + :param passive: indicates loading behavior for the attribute + if the value is not already present. This is a + bitflag attribute, which defaults to the symbol + :attr:`.PASSIVE_OFF` indicating all necessary SQL + should be emitted. + + .. seealso:: + + :attr:`.AttributeState.history` + + :meth:`.AttributeState.load_history` - retrieve history + using loader callables if the value is not locally present. + + """ + + return get_state_history(instance_state(obj), key, passive) + + +def get_state_history( + state: InstanceState[Any], key: str, passive: PassiveFlag = PASSIVE_OFF +) -> History: + return state.get_history(key, passive) + + +def has_parent( + cls: Type[_O], obj: _O, key: str, optimistic: bool = False +) -> bool: + """TODO""" + manager = manager_of_class(cls) + state = instance_state(obj) + return manager.has_parent(state, key, optimistic) + + +def register_attribute( + class_: Type[_O], + key: str, + *, + comparator: interfaces.PropComparator[_T], + parententity: _InternalEntityType[_O], + doc: Optional[str] = None, + **kw: Any, +) -> InstrumentedAttribute[_T]: + desc = register_descriptor( + class_, key, comparator=comparator, parententity=parententity, doc=doc + ) + register_attribute_impl(class_, key, **kw) + return desc + + +def register_attribute_impl( + class_: Type[_O], + key: str, + uselist: bool = False, + callable_: Optional[_LoaderCallable] = None, + useobject: bool = False, + impl_class: Optional[Type[AttributeImpl]] = None, + backref: Optional[str] = None, + **kw: Any, +) -> QueryableAttribute[Any]: + manager = manager_of_class(class_) + if uselist: + factory = kw.pop("typecallable", None) + typecallable = manager.instrument_collection_class( + key, factory or list + ) + else: + typecallable = kw.pop("typecallable", None) + + dispatch = cast( + "_Dispatch[QueryableAttribute[Any]]", manager[key].dispatch + ) # noqa: E501 + + impl: AttributeImpl + + if impl_class: + # TODO: this appears to be the WriteOnlyAttributeImpl / + # DynamicAttributeImpl constructor which is hardcoded + impl = cast("Type[WriteOnlyAttributeImpl]", impl_class)( + class_, key, dispatch, **kw + ) + elif uselist: + impl = CollectionAttributeImpl( + class_, key, callable_, dispatch, typecallable=typecallable, **kw + ) + elif useobject: + impl = ScalarObjectAttributeImpl( + class_, key, callable_, dispatch, **kw + ) + else: + impl = ScalarAttributeImpl(class_, key, callable_, dispatch, **kw) + + manager[key].impl = impl + + if backref: + backref_listeners(manager[key], backref, uselist) + + manager.post_configure_attribute(key) + return manager[key] + + +def register_descriptor( + class_: Type[Any], + key: str, + *, + comparator: interfaces.PropComparator[_T], + parententity: _InternalEntityType[Any], + doc: Optional[str] = None, +) -> InstrumentedAttribute[_T]: + manager = manager_of_class(class_) + + descriptor = InstrumentedAttribute( + class_, key, comparator=comparator, parententity=parententity + ) + + descriptor.__doc__ = doc # type: ignore + + manager.instrument_attribute(key, descriptor) + return descriptor + + +def unregister_attribute(class_: Type[Any], key: str) -> None: + manager_of_class(class_).uninstrument_attribute(key) + + +def init_collection(obj: object, key: str) -> CollectionAdapter: + """Initialize a collection attribute and return the collection adapter. + + This function is used to provide direct access to collection internals + for a previously unloaded attribute. e.g.:: + + collection_adapter = init_collection(someobject, "elements") + for elem in values: + collection_adapter.append_without_event(elem) + + For an easier way to do the above, see + :func:`~sqlalchemy.orm.attributes.set_committed_value`. + + :param obj: a mapped object + + :param key: string attribute name where the collection is located. + + """ + state = instance_state(obj) + dict_ = state.dict + return init_state_collection(state, dict_, key) + + +def init_state_collection( + state: InstanceState[Any], dict_: _InstanceDict, key: str +) -> CollectionAdapter: + """Initialize a collection attribute and return the collection adapter. + + Discards any existing collection which may be there. + + """ + attr = state.manager[key].impl + + if TYPE_CHECKING: + assert isinstance(attr, HasCollectionAdapter) + + old = dict_.pop(key, None) # discard old collection + if old is not None: + old_collection = old._sa_adapter + attr._dispose_previous_collection(state, old, old_collection, False) + + user_data = attr._default_value(state, dict_) + adapter: CollectionAdapter = attr.get_collection( + state, dict_, user_data, passive=PassiveFlag.PASSIVE_NO_FETCH + ) + adapter._reset_empty() + + return adapter + + +def set_committed_value(instance: object, key: str, value: Any) -> None: + """Set the value of an attribute with no history events. + + Cancels any previous history present. The value should be + a scalar value for scalar-holding attributes, or + an iterable for any collection-holding attribute. + + This is the same underlying method used when a lazy loader + fires off and loads additional data from the database. + In particular, this method can be used by application code + which has loaded additional attributes or collections through + separate queries, which can then be attached to an instance + as though it were part of its original loaded state. + + """ + state, dict_ = instance_state(instance), instance_dict(instance) + state.manager[key].impl.set_committed_value(state, dict_, value) + + +def set_attribute( + instance: object, + key: str, + value: Any, + initiator: Optional[AttributeEventToken] = None, +) -> None: + """Set the value of an attribute, firing history events. + + This function may be used regardless of instrumentation + applied directly to the class, i.e. no descriptors are required. + Custom attribute management schemes will need to make usage + of this method to establish attribute state as understood + by SQLAlchemy. + + :param instance: the object that will be modified + + :param key: string name of the attribute + + :param value: value to assign + + :param initiator: an instance of :class:`.Event` that would have + been propagated from a previous event listener. This argument + is used when the :func:`.set_attribute` function is being used within + an existing event listening function where an :class:`.Event` object + is being supplied; the object may be used to track the origin of the + chain of events. + + .. versionadded:: 1.2.3 + + """ + state, dict_ = instance_state(instance), instance_dict(instance) + state.manager[key].impl.set(state, dict_, value, initiator) + + +def get_attribute(instance: object, key: str) -> Any: + """Get the value of an attribute, firing any callables required. + + This function may be used regardless of instrumentation + applied directly to the class, i.e. no descriptors are required. + Custom attribute management schemes will need to make usage + of this method to make usage of attribute state as understood + by SQLAlchemy. + + """ + state, dict_ = instance_state(instance), instance_dict(instance) + return state.manager[key].impl.get(state, dict_) + + +def del_attribute(instance: object, key: str) -> None: + """Delete the value of an attribute, firing history events. + + This function may be used regardless of instrumentation + applied directly to the class, i.e. no descriptors are required. + Custom attribute management schemes will need to make usage + of this method to establish attribute state as understood + by SQLAlchemy. + + """ + state, dict_ = instance_state(instance), instance_dict(instance) + state.manager[key].impl.delete(state, dict_) + + +def flag_modified(instance: object, key: str) -> None: + """Mark an attribute on an instance as 'modified'. + + This sets the 'modified' flag on the instance and + establishes an unconditional change event for the given attribute. + The attribute must have a value present, else an + :class:`.InvalidRequestError` is raised. + + To mark an object "dirty" without referring to any specific attribute + so that it is considered within a flush, use the + :func:`.attributes.flag_dirty` call. + + .. seealso:: + + :func:`.attributes.flag_dirty` + + """ + state, dict_ = instance_state(instance), instance_dict(instance) + impl = state.manager[key].impl + impl.dispatch.modified(state, impl._modified_token) + state._modified_event(dict_, impl, NO_VALUE, is_userland=True) + + +def flag_dirty(instance: object) -> None: + """Mark an instance as 'dirty' without any specific attribute mentioned. + + This is a special operation that will allow the object to travel through + the flush process for interception by events such as + :meth:`.SessionEvents.before_flush`. Note that no SQL will be emitted in + the flush process for an object that has no changes, even if marked dirty + via this method. However, a :meth:`.SessionEvents.before_flush` handler + will be able to see the object in the :attr:`.Session.dirty` collection and + may establish changes on it, which will then be included in the SQL + emitted. + + .. versionadded:: 1.2 + + .. seealso:: + + :func:`.attributes.flag_modified` + + """ + + state, dict_ = instance_state(instance), instance_dict(instance) + state._modified_event(dict_, None, NO_VALUE, is_userland=True) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/base.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1c789627bc2a1a6a16092ee7ce940e2b2058a261 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/base.py @@ -0,0 +1,971 @@ +# orm/base.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Constants and rudimental functions used throughout the ORM.""" + +from __future__ import annotations + +from enum import Enum +import operator +import typing +from typing import Any +from typing import Callable +from typing import Dict +from typing import Generic +from typing import no_type_check +from typing import Optional +from typing import overload +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import exc +from ._typing import insp_is_mapper +from .. import exc as sa_exc +from .. import inspection +from .. import util +from ..sql import roles +from ..sql.elements import SQLColumnExpression +from ..sql.elements import SQLCoreOperations +from ..util import FastIntFlag +from ..util.langhelpers import TypingOnly +from ..util.typing import Literal + +if typing.TYPE_CHECKING: + from ._typing import _EntityType + from ._typing import _ExternalEntityType + from ._typing import _InternalEntityType + from .attributes import InstrumentedAttribute + from .dynamic import AppenderQuery + from .instrumentation import ClassManager + from .interfaces import PropComparator + from .mapper import Mapper + from .state import InstanceState + from .util import AliasedClass + from .writeonly import WriteOnlyCollection + from ..sql._typing import _ColumnExpressionArgument + from ..sql._typing import _InfoType + from ..sql.elements import ColumnElement + from ..sql.operators import OperatorType + +_T = TypeVar("_T", bound=Any) +_T_co = TypeVar("_T_co", bound=Any, covariant=True) + +_O = TypeVar("_O", bound=object) + + +class LoaderCallableStatus(Enum): + PASSIVE_NO_RESULT = 0 + """Symbol returned by a loader callable or other attribute/history + retrieval operation when a value could not be determined, based + on loader callable flags. + """ + + PASSIVE_CLASS_MISMATCH = 1 + """Symbol indicating that an object is locally present for a given + primary key identity but it is not of the requested class. The + return value is therefore None and no SQL should be emitted.""" + + ATTR_WAS_SET = 2 + """Symbol returned by a loader callable to indicate the + retrieved value, or values, were assigned to their attributes + on the target object. + """ + + ATTR_EMPTY = 3 + """Symbol used internally to indicate an attribute had no callable.""" + + NO_VALUE = 4 + """Symbol which may be placed as the 'previous' value of an attribute, + indicating no value was loaded for an attribute when it was modified, + and flags indicated we were not to load it. + """ + + NEVER_SET = NO_VALUE + """ + Synonymous with NO_VALUE + + .. versionchanged:: 1.4 NEVER_SET was merged with NO_VALUE + + """ + + +( + PASSIVE_NO_RESULT, + PASSIVE_CLASS_MISMATCH, + ATTR_WAS_SET, + ATTR_EMPTY, + NO_VALUE, +) = tuple(LoaderCallableStatus) + +NEVER_SET = NO_VALUE + + +class PassiveFlag(FastIntFlag): + """Bitflag interface that passes options onto loader callables""" + + NO_CHANGE = 0 + """No callables or SQL should be emitted on attribute access + and no state should change + """ + + CALLABLES_OK = 1 + """Loader callables can be fired off if a value + is not present. + """ + + SQL_OK = 2 + """Loader callables can emit SQL at least on scalar value attributes.""" + + RELATED_OBJECT_OK = 4 + """Callables can use SQL to load related objects as well + as scalar value attributes. + """ + + INIT_OK = 8 + """Attributes should be initialized with a blank + value (None or an empty collection) upon get, if no other + value can be obtained. + """ + + NON_PERSISTENT_OK = 16 + """Callables can be emitted if the parent is not persistent.""" + + LOAD_AGAINST_COMMITTED = 32 + """Callables should use committed values as primary/foreign keys during a + load. + """ + + NO_AUTOFLUSH = 64 + """Loader callables should disable autoflush.""" + + NO_RAISE = 128 + """Loader callables should not raise any assertions""" + + DEFERRED_HISTORY_LOAD = 256 + """indicates special load of the previous value of an attribute""" + + INCLUDE_PENDING_MUTATIONS = 512 + + # pre-packaged sets of flags used as inputs + PASSIVE_OFF = ( + RELATED_OBJECT_OK | NON_PERSISTENT_OK | INIT_OK | CALLABLES_OK | SQL_OK + ) + "Callables can be emitted in all cases." + + PASSIVE_RETURN_NO_VALUE = PASSIVE_OFF ^ INIT_OK + """PASSIVE_OFF ^ INIT_OK""" + + PASSIVE_NO_INITIALIZE = PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK + "PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK" + + PASSIVE_NO_FETCH = PASSIVE_OFF ^ SQL_OK + "PASSIVE_OFF ^ SQL_OK" + + PASSIVE_NO_FETCH_RELATED = PASSIVE_OFF ^ RELATED_OBJECT_OK + "PASSIVE_OFF ^ RELATED_OBJECT_OK" + + PASSIVE_ONLY_PERSISTENT = PASSIVE_OFF ^ NON_PERSISTENT_OK + "PASSIVE_OFF ^ NON_PERSISTENT_OK" + + PASSIVE_MERGE = PASSIVE_OFF | NO_RAISE + """PASSIVE_OFF | NO_RAISE + + Symbol used specifically for session.merge() and similar cases + + """ + + +( + NO_CHANGE, + CALLABLES_OK, + SQL_OK, + RELATED_OBJECT_OK, + INIT_OK, + NON_PERSISTENT_OK, + LOAD_AGAINST_COMMITTED, + NO_AUTOFLUSH, + NO_RAISE, + DEFERRED_HISTORY_LOAD, + INCLUDE_PENDING_MUTATIONS, + PASSIVE_OFF, + PASSIVE_RETURN_NO_VALUE, + PASSIVE_NO_INITIALIZE, + PASSIVE_NO_FETCH, + PASSIVE_NO_FETCH_RELATED, + PASSIVE_ONLY_PERSISTENT, + PASSIVE_MERGE, +) = PassiveFlag.__members__.values() + +DEFAULT_MANAGER_ATTR = "_sa_class_manager" +DEFAULT_STATE_ATTR = "_sa_instance_state" + + +class EventConstants(Enum): + EXT_CONTINUE = 1 + EXT_STOP = 2 + EXT_SKIP = 3 + NO_KEY = 4 + """indicates an :class:`.AttributeEvent` event that did not have any + key argument. + + .. versionadded:: 2.0 + + """ + + +EXT_CONTINUE, EXT_STOP, EXT_SKIP, NO_KEY = tuple(EventConstants) + + +class RelationshipDirection(Enum): + """enumeration which indicates the 'direction' of a + :class:`_orm.RelationshipProperty`. + + :class:`.RelationshipDirection` is accessible from the + :attr:`_orm.Relationship.direction` attribute of + :class:`_orm.RelationshipProperty`. + + """ + + ONETOMANY = 1 + """Indicates the one-to-many direction for a :func:`_orm.relationship`. + + This symbol is typically used by the internals but may be exposed within + certain API features. + + """ + + MANYTOONE = 2 + """Indicates the many-to-one direction for a :func:`_orm.relationship`. + + This symbol is typically used by the internals but may be exposed within + certain API features. + + """ + + MANYTOMANY = 3 + """Indicates the many-to-many direction for a :func:`_orm.relationship`. + + This symbol is typically used by the internals but may be exposed within + certain API features. + + """ + + +ONETOMANY, MANYTOONE, MANYTOMANY = tuple(RelationshipDirection) + + +class InspectionAttrExtensionType(Enum): + """Symbols indicating the type of extension that a + :class:`.InspectionAttr` is part of.""" + + +class NotExtension(InspectionAttrExtensionType): + NOT_EXTENSION = "not_extension" + """Symbol indicating an :class:`InspectionAttr` that's + not part of sqlalchemy.ext. + + Is assigned to the :attr:`.InspectionAttr.extension_type` + attribute. + + """ + + +_never_set = frozenset([NEVER_SET]) + +_none_set = frozenset([None, NEVER_SET, PASSIVE_NO_RESULT]) + +_none_only_set = frozenset([None]) + +_SET_DEFERRED_EXPIRED = util.symbol("SET_DEFERRED_EXPIRED") + +_DEFER_FOR_STATE = util.symbol("DEFER_FOR_STATE") + +_RAISE_FOR_STATE = util.symbol("RAISE_FOR_STATE") + + +_F = TypeVar("_F", bound=Callable[..., Any]) +_Self = TypeVar("_Self") + + +def _assertions( + *assertions: Any, +) -> Callable[[_F], _F]: + @util.decorator + def generate(fn: _F, self: _Self, *args: Any, **kw: Any) -> _Self: + for assertion in assertions: + assertion(self, fn.__name__) + fn(self, *args, **kw) + return self + + return generate + + +if TYPE_CHECKING: + + def manager_of_class(cls: Type[_O]) -> ClassManager[_O]: ... + + @overload + def opt_manager_of_class(cls: AliasedClass[Any]) -> None: ... + + @overload + def opt_manager_of_class( + cls: _ExternalEntityType[_O], + ) -> Optional[ClassManager[_O]]: ... + + def opt_manager_of_class( + cls: _ExternalEntityType[_O], + ) -> Optional[ClassManager[_O]]: ... + + def instance_state(instance: _O) -> InstanceState[_O]: ... + + def instance_dict(instance: object) -> Dict[str, Any]: ... + +else: + # these can be replaced by sqlalchemy.ext.instrumentation + # if augmented class instrumentation is enabled. + + def manager_of_class(cls): + try: + return cls.__dict__[DEFAULT_MANAGER_ATTR] + except KeyError as ke: + raise exc.UnmappedClassError( + cls, f"Can't locate an instrumentation manager for class {cls}" + ) from ke + + def opt_manager_of_class(cls): + return cls.__dict__.get(DEFAULT_MANAGER_ATTR) + + instance_state = operator.attrgetter(DEFAULT_STATE_ATTR) + + instance_dict = operator.attrgetter("__dict__") + + +def instance_str(instance: object) -> str: + """Return a string describing an instance.""" + + return state_str(instance_state(instance)) + + +def state_str(state: InstanceState[Any]) -> str: + """Return a string describing an instance via its InstanceState.""" + + if state is None: + return "None" + else: + return "<%s at 0x%x>" % (state.class_.__name__, id(state.obj())) + + +def state_class_str(state: InstanceState[Any]) -> str: + """Return a string describing an instance's class via its + InstanceState. + """ + + if state is None: + return "None" + else: + return "<%s>" % (state.class_.__name__,) + + +def attribute_str(instance: object, attribute: str) -> str: + return instance_str(instance) + "." + attribute + + +def state_attribute_str(state: InstanceState[Any], attribute: str) -> str: + return state_str(state) + "." + attribute + + +def object_mapper(instance: _T) -> Mapper[_T]: + """Given an object, return the primary Mapper associated with the object + instance. + + Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError` + if no mapping is configured. + + This function is available via the inspection system as:: + + inspect(instance).mapper + + Using the inspection system will raise + :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is + not part of a mapping. + + """ + return object_state(instance).mapper + + +def object_state(instance: _T) -> InstanceState[_T]: + """Given an object, return the :class:`.InstanceState` + associated with the object. + + Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError` + if no mapping is configured. + + Equivalent functionality is available via the :func:`_sa.inspect` + function as:: + + inspect(instance) + + Using the inspection system will raise + :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is + not part of a mapping. + + """ + state = _inspect_mapped_object(instance) + if state is None: + raise exc.UnmappedInstanceError(instance) + else: + return state + + +@inspection._inspects(object) +def _inspect_mapped_object(instance: _T) -> Optional[InstanceState[_T]]: + try: + return instance_state(instance) + except (exc.UnmappedClassError,) + exc.NO_STATE: + return None + + +def _class_to_mapper( + class_or_mapper: Union[Mapper[_T], Type[_T]], +) -> Mapper[_T]: + # can't get mypy to see an overload for this + insp = inspection.inspect(class_or_mapper, False) + if insp is not None: + return insp.mapper # type: ignore + else: + assert isinstance(class_or_mapper, type) + raise exc.UnmappedClassError(class_or_mapper) + + +def _mapper_or_none( + entity: Union[Type[_T], _InternalEntityType[_T]], +) -> Optional[Mapper[_T]]: + """Return the :class:`_orm.Mapper` for the given class or None if the + class is not mapped. + """ + + # can't get mypy to see an overload for this + insp = inspection.inspect(entity, False) + if insp is not None: + return insp.mapper # type: ignore + else: + return None + + +def _is_mapped_class(entity: Any) -> bool: + """Return True if the given object is a mapped class, + :class:`_orm.Mapper`, or :class:`.AliasedClass`. + """ + + insp = inspection.inspect(entity, False) + return ( + insp is not None + and not insp.is_clause_element + and (insp.is_mapper or insp.is_aliased_class) + ) + + +def _is_aliased_class(entity: Any) -> bool: + insp = inspection.inspect(entity, False) + return insp is not None and getattr(insp, "is_aliased_class", False) + + +@no_type_check +def _entity_descriptor(entity: _EntityType[Any], key: str) -> Any: + """Return a class attribute given an entity and string name. + + May return :class:`.InstrumentedAttribute` or user-defined + attribute. + + """ + insp = inspection.inspect(entity) + if insp.is_selectable: + description = entity + entity = insp.c + elif insp.is_aliased_class: + entity = insp.entity + description = entity + elif hasattr(insp, "mapper"): + description = entity = insp.mapper.class_ + else: + description = entity + + try: + return getattr(entity, key) + except AttributeError as err: + raise sa_exc.InvalidRequestError( + "Entity '%s' has no property '%s'" % (description, key) + ) from err + + +if TYPE_CHECKING: + + def _state_mapper(state: InstanceState[_O]) -> Mapper[_O]: ... + +else: + _state_mapper = util.dottedgetter("manager.mapper") + + +def _inspect_mapped_class( + class_: Type[_O], configure: bool = False +) -> Optional[Mapper[_O]]: + try: + class_manager = opt_manager_of_class(class_) + if class_manager is None or not class_manager.is_mapped: + return None + mapper = class_manager.mapper + except exc.NO_STATE: + return None + else: + if configure: + mapper._check_configure() + return mapper + + +def _parse_mapper_argument(arg: Union[Mapper[_O], Type[_O]]) -> Mapper[_O]: + insp = inspection.inspect(arg, raiseerr=False) + if insp_is_mapper(insp): + return insp + + raise sa_exc.ArgumentError(f"Mapper or mapped class expected, got {arg!r}") + + +def class_mapper(class_: Type[_O], configure: bool = True) -> Mapper[_O]: + """Given a class, return the primary :class:`_orm.Mapper` associated + with the key. + + Raises :exc:`.UnmappedClassError` if no mapping is configured + on the given class, or :exc:`.ArgumentError` if a non-class + object is passed. + + Equivalent functionality is available via the :func:`_sa.inspect` + function as:: + + inspect(some_mapped_class) + + Using the inspection system will raise + :class:`sqlalchemy.exc.NoInspectionAvailable` if the class is not mapped. + + """ + mapper = _inspect_mapped_class(class_, configure=configure) + if mapper is None: + if not isinstance(class_, type): + raise sa_exc.ArgumentError( + "Class object expected, got '%r'." % (class_,) + ) + raise exc.UnmappedClassError(class_) + else: + return mapper + + +class InspectionAttr: + """A base class applied to all ORM objects and attributes that are + related to things that can be returned by the :func:`_sa.inspect` function. + + The attributes defined here allow the usage of simple boolean + checks to test basic facts about the object returned. + + While the boolean checks here are basically the same as using + the Python isinstance() function, the flags here can be used without + the need to import all of these classes, and also such that + the SQLAlchemy class system can change while leaving the flags + here intact for forwards-compatibility. + + """ + + __slots__: Tuple[str, ...] = () + + is_selectable = False + """Return True if this object is an instance of + :class:`_expression.Selectable`.""" + + is_aliased_class = False + """True if this object is an instance of :class:`.AliasedClass`.""" + + is_instance = False + """True if this object is an instance of :class:`.InstanceState`.""" + + is_mapper = False + """True if this object is an instance of :class:`_orm.Mapper`.""" + + is_bundle = False + """True if this object is an instance of :class:`.Bundle`.""" + + is_property = False + """True if this object is an instance of :class:`.MapperProperty`.""" + + is_attribute = False + """True if this object is a Python :term:`descriptor`. + + This can refer to one of many types. Usually a + :class:`.QueryableAttribute` which handles attributes events on behalf + of a :class:`.MapperProperty`. But can also be an extension type + such as :class:`.AssociationProxy` or :class:`.hybrid_property`. + The :attr:`.InspectionAttr.extension_type` will refer to a constant + identifying the specific subtype. + + .. seealso:: + + :attr:`_orm.Mapper.all_orm_descriptors` + + """ + + _is_internal_proxy = False + """True if this object is an internal proxy object. + + .. versionadded:: 1.2.12 + + """ + + is_clause_element = False + """True if this object is an instance of + :class:`_expression.ClauseElement`.""" + + extension_type: InspectionAttrExtensionType = NotExtension.NOT_EXTENSION + """The extension type, if any. + Defaults to :attr:`.interfaces.NotExtension.NOT_EXTENSION` + + .. seealso:: + + :class:`.HybridExtensionType` + + :class:`.AssociationProxyExtensionType` + + """ + + +class InspectionAttrInfo(InspectionAttr): + """Adds the ``.info`` attribute to :class:`.InspectionAttr`. + + The rationale for :class:`.InspectionAttr` vs. :class:`.InspectionAttrInfo` + is that the former is compatible as a mixin for classes that specify + ``__slots__``; this is essentially an implementation artifact. + + """ + + __slots__ = () + + @util.ro_memoized_property + def info(self) -> _InfoType: + """Info dictionary associated with the object, allowing user-defined + data to be associated with this :class:`.InspectionAttr`. + + The dictionary is generated when first accessed. Alternatively, + it can be specified as a constructor argument to the + :func:`.column_property`, :func:`_orm.relationship`, or + :func:`.composite` + functions. + + .. seealso:: + + :attr:`.QueryableAttribute.info` + + :attr:`.SchemaItem.info` + + """ + return {} + + +class SQLORMOperations(SQLCoreOperations[_T_co], TypingOnly): + __slots__ = () + + if typing.TYPE_CHECKING: + + def of_type( + self, class_: _EntityType[Any] + ) -> PropComparator[_T_co]: ... + + def and_( + self, *criteria: _ColumnExpressionArgument[bool] + ) -> PropComparator[bool]: ... + + def any( # noqa: A001 + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: ... + + def has( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: ... + + +class ORMDescriptor(Generic[_T_co], TypingOnly): + """Represent any Python descriptor that provides a SQL expression + construct at the class level.""" + + __slots__ = () + + if typing.TYPE_CHECKING: + + @overload + def __get__( + self, instance: Any, owner: Literal[None] + ) -> ORMDescriptor[_T_co]: ... + + @overload + def __get__( + self, instance: Literal[None], owner: Any + ) -> SQLCoreOperations[_T_co]: ... + + @overload + def __get__(self, instance: object, owner: Any) -> _T_co: ... + + def __get__( + self, instance: object, owner: Any + ) -> Union[ORMDescriptor[_T_co], SQLCoreOperations[_T_co], _T_co]: ... + + +class _MappedAnnotationBase(Generic[_T_co], TypingOnly): + """common class for Mapped and similar ORM container classes. + + these are classes that can appear on the left side of an ORM declarative + mapping, containing a mapped class or in some cases a collection + surrounding a mapped class. + + """ + + __slots__ = () + + +class SQLORMExpression( + SQLORMOperations[_T_co], SQLColumnExpression[_T_co], TypingOnly +): + """A type that may be used to indicate any ORM-level attribute or + object that acts in place of one, in the context of SQL expression + construction. + + :class:`.SQLORMExpression` extends from the Core + :class:`.SQLColumnExpression` to add additional SQL methods that are ORM + specific, such as :meth:`.PropComparator.of_type`, and is part of the bases + for :class:`.InstrumentedAttribute`. It may be used in :pep:`484` typing to + indicate arguments or return values that should behave as ORM-level + attribute expressions. + + .. versionadded:: 2.0.0b4 + + + """ + + __slots__ = () + + +class Mapped( + SQLORMExpression[_T_co], + ORMDescriptor[_T_co], + _MappedAnnotationBase[_T_co], + roles.DDLConstraintColumnRole, +): + """Represent an ORM mapped attribute on a mapped class. + + This class represents the complete descriptor interface for any class + attribute that will have been :term:`instrumented` by the ORM + :class:`_orm.Mapper` class. Provides appropriate information to type + checkers such as pylance and mypy so that ORM-mapped attributes + are correctly typed. + + The most prominent use of :class:`_orm.Mapped` is in + the :ref:`Declarative Mapping ` form + of :class:`_orm.Mapper` configuration, where used explicitly it drives + the configuration of ORM attributes such as :func:`_orm.mapped_class` + and :func:`_orm.relationship`. + + .. seealso:: + + :ref:`orm_explicit_declarative_base` + + :ref:`orm_declarative_table` + + .. tip:: + + The :class:`_orm.Mapped` class represents attributes that are handled + directly by the :class:`_orm.Mapper` class. It does not include other + Python descriptor classes that are provided as extensions, including + :ref:`hybrids_toplevel` and the :ref:`associationproxy_toplevel`. + While these systems still make use of ORM-specific superclasses + and structures, they are not :term:`instrumented` by the + :class:`_orm.Mapper` and instead provide their own functionality + when they are accessed on a class. + + .. versionadded:: 1.4 + + + """ + + __slots__ = () + + if typing.TYPE_CHECKING: + + @overload + def __get__( + self, instance: None, owner: Any + ) -> InstrumentedAttribute[_T_co]: ... + + @overload + def __get__(self, instance: object, owner: Any) -> _T_co: ... + + def __get__( + self, instance: Optional[object], owner: Any + ) -> Union[InstrumentedAttribute[_T_co], _T_co]: ... + + @classmethod + def _empty_constructor(cls, arg1: Any) -> Mapped[_T_co]: ... + + def __set__( + self, instance: Any, value: Union[SQLCoreOperations[_T_co], _T_co] + ) -> None: ... + + def __delete__(self, instance: Any) -> None: ... + + +class _MappedAttribute(Generic[_T_co], TypingOnly): + """Mixin for attributes which should be replaced by mapper-assigned + attributes. + + """ + + __slots__ = () + + +class _DeclarativeMapped(Mapped[_T_co], _MappedAttribute[_T_co]): + """Mixin for :class:`.MapperProperty` subclasses that allows them to + be compatible with ORM-annotated declarative mappings. + + """ + + __slots__ = () + + # MappedSQLExpression, Relationship, Composite etc. dont actually do + # SQL expression behavior. yet there is code that compares them with + # __eq__(), __ne__(), etc. Since #8847 made Mapped even more full + # featured including ColumnOperators, we need to have those methods + # be no-ops for these objects, so return NotImplemented to fall back + # to normal comparison behavior. + def operate(self, op: OperatorType, *other: Any, **kwargs: Any) -> Any: + return NotImplemented + + __sa_operate__ = operate + + def reverse_operate( + self, op: OperatorType, other: Any, **kwargs: Any + ) -> Any: + return NotImplemented + + +class DynamicMapped(_MappedAnnotationBase[_T_co]): + """Represent the ORM mapped attribute type for a "dynamic" relationship. + + The :class:`_orm.DynamicMapped` type annotation may be used in an + :ref:`Annotated Declarative Table ` mapping + to indicate that the ``lazy="dynamic"`` loader strategy should be used + for a particular :func:`_orm.relationship`. + + .. legacy:: The "dynamic" lazy loader strategy is the legacy form of what + is now the "write_only" strategy described in the section + :ref:`write_only_relationship`. + + E.g.:: + + class User(Base): + __tablename__ = "user" + id: Mapped[int] = mapped_column(primary_key=True) + addresses: DynamicMapped[Address] = relationship( + cascade="all,delete-orphan" + ) + + See the section :ref:`dynamic_relationship` for background. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`dynamic_relationship` - complete background + + :class:`.WriteOnlyMapped` - fully 2.0 style version + + """ + + __slots__ = () + + if TYPE_CHECKING: + + @overload + def __get__( + self, instance: None, owner: Any + ) -> InstrumentedAttribute[_T_co]: ... + + @overload + def __get__( + self, instance: object, owner: Any + ) -> AppenderQuery[_T_co]: ... + + def __get__( + self, instance: Optional[object], owner: Any + ) -> Union[InstrumentedAttribute[_T_co], AppenderQuery[_T_co]]: ... + + def __set__( + self, instance: Any, value: typing.Collection[_T_co] + ) -> None: ... + + +class WriteOnlyMapped(_MappedAnnotationBase[_T_co]): + """Represent the ORM mapped attribute type for a "write only" relationship. + + The :class:`_orm.WriteOnlyMapped` type annotation may be used in an + :ref:`Annotated Declarative Table ` mapping + to indicate that the ``lazy="write_only"`` loader strategy should be used + for a particular :func:`_orm.relationship`. + + E.g.:: + + class User(Base): + __tablename__ = "user" + id: Mapped[int] = mapped_column(primary_key=True) + addresses: WriteOnlyMapped[Address] = relationship( + cascade="all,delete-orphan" + ) + + See the section :ref:`write_only_relationship` for background. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`write_only_relationship` - complete background + + :class:`.DynamicMapped` - includes legacy :class:`_orm.Query` support + + """ + + __slots__ = () + + if TYPE_CHECKING: + + @overload + def __get__( + self, instance: None, owner: Any + ) -> InstrumentedAttribute[_T_co]: ... + + @overload + def __get__( + self, instance: object, owner: Any + ) -> WriteOnlyCollection[_T_co]: ... + + def __get__( + self, instance: Optional[object], owner: Any + ) -> Union[ + InstrumentedAttribute[_T_co], WriteOnlyCollection[_T_co] + ]: ... + + def __set__( + self, instance: Any, value: typing.Collection[_T_co] + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/bulk_persistence.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/bulk_persistence.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe72f10072dfcd0ad634e06834f6fac96f43076 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/bulk_persistence.py @@ -0,0 +1,2135 @@ +# orm/bulk_persistence.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + + +"""additional ORM persistence classes related to "bulk" operations, +specifically outside of the flush() process. + +""" + +from __future__ import annotations + +from typing import Any +from typing import cast +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import overload +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import attributes +from . import context +from . import evaluator +from . import exc as orm_exc +from . import loading +from . import persistence +from .base import NO_VALUE +from .context import AbstractORMCompileState +from .context import FromStatement +from .context import ORMFromStatementCompileState +from .context import QueryContext +from .. import exc as sa_exc +from .. import util +from ..engine import Dialect +from ..engine import result as _result +from ..sql import coercions +from ..sql import dml +from ..sql import expression +from ..sql import roles +from ..sql import select +from ..sql import sqltypes +from ..sql.base import _entity_namespace_key +from ..sql.base import CompileState +from ..sql.base import Options +from ..sql.dml import DeleteDMLState +from ..sql.dml import InsertDMLState +from ..sql.dml import UpdateDMLState +from ..util import EMPTY_DICT +from ..util.typing import Literal + +if TYPE_CHECKING: + from ._typing import DMLStrategyArgument + from ._typing import OrmExecuteOptionsParameter + from ._typing import SynchronizeSessionArgument + from .mapper import Mapper + from .session import _BindArguments + from .session import ORMExecuteState + from .session import Session + from .session import SessionTransaction + from .state import InstanceState + from ..engine import Connection + from ..engine import cursor + from ..engine.interfaces import _CoreAnyExecuteParams + +_O = TypeVar("_O", bound=object) + + +@overload +def _bulk_insert( + mapper: Mapper[_O], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + return_defaults: bool, + render_nulls: bool, + use_orm_insert_stmt: Literal[None] = ..., + execution_options: Optional[OrmExecuteOptionsParameter] = ..., +) -> None: ... + + +@overload +def _bulk_insert( + mapper: Mapper[_O], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + return_defaults: bool, + render_nulls: bool, + use_orm_insert_stmt: Optional[dml.Insert] = ..., + execution_options: Optional[OrmExecuteOptionsParameter] = ..., +) -> cursor.CursorResult[Any]: ... + + +def _bulk_insert( + mapper: Mapper[_O], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + return_defaults: bool, + render_nulls: bool, + use_orm_insert_stmt: Optional[dml.Insert] = None, + execution_options: Optional[OrmExecuteOptionsParameter] = None, +) -> Optional[cursor.CursorResult[Any]]: + base_mapper = mapper.base_mapper + + if session_transaction.session.connection_callable: + raise NotImplementedError( + "connection_callable / per-instance sharding " + "not supported in bulk_insert()" + ) + + if isstates: + if TYPE_CHECKING: + mappings = cast(Iterable[InstanceState[_O]], mappings) + + if return_defaults: + # list of states allows us to attach .key for return_defaults case + states = [(state, state.dict) for state in mappings] + mappings = [dict_ for (state, dict_) in states] + else: + mappings = [state.dict for state in mappings] + else: + if TYPE_CHECKING: + mappings = cast(Iterable[Dict[str, Any]], mappings) + + if return_defaults: + # use dictionaries given, so that newly populated defaults + # can be delivered back to the caller (see #11661). This is **not** + # compatible with other use cases such as a session-executed + # insert() construct, as this will confuse the case of + # insert-per-subclass for joined inheritance cases (see + # test_bulk_statements.py::BulkDMLReturningJoinedInhTest). + # + # So in this conditional, we have **only** called + # session.bulk_insert_mappings() which does not have this + # requirement + mappings = list(mappings) + else: + # for all other cases we need to establish a local dictionary + # so that the incoming dictionaries aren't mutated + mappings = [dict(m) for m in mappings] + _expand_composites(mapper, mappings) + + connection = session_transaction.connection(base_mapper) + + return_result: Optional[cursor.CursorResult[Any]] = None + + mappers_to_run = [ + (table, mp) + for table, mp in base_mapper._sorted_tables.items() + if table in mapper._pks_by_table + ] + + if return_defaults: + # not used by new-style bulk inserts, only used for legacy + bookkeeping = True + elif len(mappers_to_run) > 1: + # if we have more than one table, mapper to run where we will be + # either horizontally splicing, or copying values between tables, + # we need the "bookkeeping" / deterministic returning order + bookkeeping = True + else: + bookkeeping = False + + for table, super_mapper in mappers_to_run: + # find bindparams in the statement. For bulk, we don't really know if + # a key in the params applies to a different table since we are + # potentially inserting for multiple tables here; looking at the + # bindparam() is a lot more direct. in most cases this will + # use _generate_cache_key() which is memoized, although in practice + # the ultimate statement that's executed is probably not the same + # object so that memoization might not matter much. + extra_bp_names = ( + [ + b.key + for b in use_orm_insert_stmt._get_embedded_bindparams() + if b.key in mappings[0] + ] + if use_orm_insert_stmt is not None + else () + ) + + records = ( + ( + None, + state_dict, + params, + mapper, + connection, + value_params, + has_all_pks, + has_all_defaults, + ) + for ( + state, + state_dict, + params, + mp, + conn, + value_params, + has_all_pks, + has_all_defaults, + ) in persistence._collect_insert_commands( + table, + ((None, mapping, mapper, connection) for mapping in mappings), + bulk=True, + return_defaults=bookkeeping, + render_nulls=render_nulls, + include_bulk_keys=extra_bp_names, + ) + ) + + result = persistence._emit_insert_statements( + base_mapper, + None, + super_mapper, + table, + records, + bookkeeping=bookkeeping, + use_orm_insert_stmt=use_orm_insert_stmt, + execution_options=execution_options, + ) + if use_orm_insert_stmt is not None: + if not use_orm_insert_stmt._returning or return_result is None: + return_result = result + elif result.returns_rows: + assert bookkeeping + return_result = return_result.splice_horizontally(result) + + if return_defaults and isstates: + identity_cls = mapper._identity_class + identity_props = [p.key for p in mapper._identity_key_props] + for state, dict_ in states: + state.key = ( + identity_cls, + tuple([dict_[key] for key in identity_props]), + None, + ) + + if use_orm_insert_stmt is not None: + assert return_result is not None + return return_result + + +@overload +def _bulk_update( + mapper: Mapper[Any], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + update_changed_only: bool, + use_orm_update_stmt: Literal[None] = ..., + enable_check_rowcount: bool = True, +) -> None: ... + + +@overload +def _bulk_update( + mapper: Mapper[Any], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + update_changed_only: bool, + use_orm_update_stmt: Optional[dml.Update] = ..., + enable_check_rowcount: bool = True, +) -> _result.Result[Any]: ... + + +def _bulk_update( + mapper: Mapper[Any], + mappings: Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]], + session_transaction: SessionTransaction, + *, + isstates: bool, + update_changed_only: bool, + use_orm_update_stmt: Optional[dml.Update] = None, + enable_check_rowcount: bool = True, +) -> Optional[_result.Result[Any]]: + base_mapper = mapper.base_mapper + + search_keys = mapper._primary_key_propkeys + if mapper._version_id_prop: + search_keys = {mapper._version_id_prop.key}.union(search_keys) + + def _changed_dict(mapper, state): + return { + k: v + for k, v in state.dict.items() + if k in state.committed_state or k in search_keys + } + + if isstates: + if update_changed_only: + mappings = [_changed_dict(mapper, state) for state in mappings] + else: + mappings = [state.dict for state in mappings] + else: + mappings = [dict(m) for m in mappings] + _expand_composites(mapper, mappings) + + if session_transaction.session.connection_callable: + raise NotImplementedError( + "connection_callable / per-instance sharding " + "not supported in bulk_update()" + ) + + connection = session_transaction.connection(base_mapper) + + # find bindparams in the statement. see _bulk_insert for similar + # notes for the insert case + extra_bp_names = ( + [ + b.key + for b in use_orm_update_stmt._get_embedded_bindparams() + if b.key in mappings[0] + ] + if use_orm_update_stmt is not None + else () + ) + + for table, super_mapper in base_mapper._sorted_tables.items(): + if not mapper.isa(super_mapper) or table not in mapper._pks_by_table: + continue + + records = persistence._collect_update_commands( + None, + table, + ( + ( + None, + mapping, + mapper, + connection, + ( + mapping[mapper._version_id_prop.key] + if mapper._version_id_prop + else None + ), + ) + for mapping in mappings + ), + bulk=True, + use_orm_update_stmt=use_orm_update_stmt, + include_bulk_keys=extra_bp_names, + ) + persistence._emit_update_statements( + base_mapper, + None, + super_mapper, + table, + records, + bookkeeping=False, + use_orm_update_stmt=use_orm_update_stmt, + enable_check_rowcount=enable_check_rowcount, + ) + + if use_orm_update_stmt is not None: + return _result.null_result() + + +def _expand_composites(mapper, mappings): + composite_attrs = mapper.composites + if not composite_attrs: + return + + composite_keys = set(composite_attrs.keys()) + populators = { + key: composite_attrs[key]._populate_composite_bulk_save_mappings_fn() + for key in composite_keys + } + for mapping in mappings: + for key in composite_keys.intersection(mapping): + populators[key](mapping) + + +class ORMDMLState(AbstractORMCompileState): + is_dml_returning = True + from_statement_ctx: Optional[ORMFromStatementCompileState] = None + + @classmethod + def _get_orm_crud_kv_pairs( + cls, mapper, statement, kv_iterator, needs_to_be_cacheable + ): + core_get_crud_kv_pairs = UpdateDMLState._get_crud_kv_pairs + + for k, v in kv_iterator: + k = coercions.expect(roles.DMLColumnRole, k) + + if isinstance(k, str): + desc = _entity_namespace_key(mapper, k, default=NO_VALUE) + if desc is NO_VALUE: + yield ( + coercions.expect(roles.DMLColumnRole, k), + ( + coercions.expect( + roles.ExpressionElementRole, + v, + type_=sqltypes.NullType(), + is_crud=True, + ) + if needs_to_be_cacheable + else v + ), + ) + else: + yield from core_get_crud_kv_pairs( + statement, + desc._bulk_update_tuples(v), + needs_to_be_cacheable, + ) + elif "entity_namespace" in k._annotations: + k_anno = k._annotations + attr = _entity_namespace_key( + k_anno["entity_namespace"], k_anno["proxy_key"] + ) + yield from core_get_crud_kv_pairs( + statement, + attr._bulk_update_tuples(v), + needs_to_be_cacheable, + ) + else: + yield ( + k, + ( + v + if not needs_to_be_cacheable + else coercions.expect( + roles.ExpressionElementRole, + v, + type_=sqltypes.NullType(), + is_crud=True, + ) + ), + ) + + @classmethod + def _get_dml_plugin_subject(cls, statement): + plugin_subject = statement.table._propagate_attrs.get("plugin_subject") + + if ( + not plugin_subject + or not plugin_subject.mapper + or plugin_subject + is not statement._propagate_attrs["plugin_subject"] + ): + return None + return plugin_subject + + @classmethod + def _get_multi_crud_kv_pairs(cls, statement, kv_iterator): + plugin_subject = cls._get_dml_plugin_subject(statement) + + if not plugin_subject: + return UpdateDMLState._get_multi_crud_kv_pairs( + statement, kv_iterator + ) + + return [ + dict( + cls._get_orm_crud_kv_pairs( + plugin_subject.mapper, statement, value_dict.items(), False + ) + ) + for value_dict in kv_iterator + ] + + @classmethod + def _get_crud_kv_pairs(cls, statement, kv_iterator, needs_to_be_cacheable): + assert ( + needs_to_be_cacheable + ), "no test coverage for needs_to_be_cacheable=False" + + plugin_subject = cls._get_dml_plugin_subject(statement) + + if not plugin_subject: + return UpdateDMLState._get_crud_kv_pairs( + statement, kv_iterator, needs_to_be_cacheable + ) + return list( + cls._get_orm_crud_kv_pairs( + plugin_subject.mapper, + statement, + kv_iterator, + needs_to_be_cacheable, + ) + ) + + @classmethod + def get_entity_description(cls, statement): + ext_info = statement.table._annotations["parententity"] + mapper = ext_info.mapper + if ext_info.is_aliased_class: + _label_name = ext_info.name + else: + _label_name = mapper.class_.__name__ + + return { + "name": _label_name, + "type": mapper.class_, + "expr": ext_info.entity, + "entity": ext_info.entity, + "table": mapper.local_table, + } + + @classmethod + def get_returning_column_descriptions(cls, statement): + def _ent_for_col(c): + return c._annotations.get("parententity", None) + + def _attr_for_col(c, ent): + if ent is None: + return c + proxy_key = c._annotations.get("proxy_key", None) + if not proxy_key: + return c + else: + return getattr(ent.entity, proxy_key, c) + + return [ + { + "name": c.key, + "type": c.type, + "expr": _attr_for_col(c, ent), + "aliased": ent.is_aliased_class, + "entity": ent.entity, + } + for c, ent in [ + (c, _ent_for_col(c)) for c in statement._all_selected_columns + ] + ] + + def _setup_orm_returning( + self, + compiler, + orm_level_statement, + dml_level_statement, + dml_mapper, + *, + use_supplemental_cols=True, + ): + """establish ORM column handlers for an INSERT, UPDATE, or DELETE + which uses explicit returning(). + + called within compilation level create_for_statement. + + The _return_orm_returning() method then receives the Result + after the statement was executed, and applies ORM loading to the + state that we first established here. + + """ + + if orm_level_statement._returning: + fs = FromStatement( + orm_level_statement._returning, + dml_level_statement, + _adapt_on_names=False, + ) + fs = fs.execution_options(**orm_level_statement._execution_options) + fs = fs.options(*orm_level_statement._with_options) + self.select_statement = fs + self.from_statement_ctx = fsc = ( + ORMFromStatementCompileState.create_for_statement(fs, compiler) + ) + fsc.setup_dml_returning_compile_state(dml_mapper) + + dml_level_statement = dml_level_statement._generate() + dml_level_statement._returning = () + + cols_to_return = [c for c in fsc.primary_columns if c is not None] + + # since we are splicing result sets together, make sure there + # are columns of some kind returned in each result set + if not cols_to_return: + cols_to_return.extend(dml_mapper.primary_key) + + if use_supplemental_cols: + dml_level_statement = dml_level_statement.return_defaults( + # this is a little weird looking, but by passing + # primary key as the main list of cols, this tells + # return_defaults to omit server-default cols (and + # actually all cols, due to some weird thing we should + # clean up in crud.py). + # Since we have cols_to_return, just return what we asked + # for (plus primary key, which ORM persistence needs since + # we likely set bookkeeping=True here, which is another + # whole thing...). We dont want to clutter the + # statement up with lots of other cols the user didn't + # ask for. see #9685 + *dml_mapper.primary_key, + supplemental_cols=cols_to_return, + ) + else: + dml_level_statement = dml_level_statement.returning( + *cols_to_return + ) + + return dml_level_statement + + @classmethod + def _return_orm_returning( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + result, + ): + execution_context = result.context + compile_state = execution_context.compiled.compile_state + + if ( + compile_state.from_statement_ctx + and not compile_state.from_statement_ctx.compile_options._is_star + ): + load_options = execution_options.get( + "_sa_orm_load_options", QueryContext.default_load_options + ) + + querycontext = QueryContext( + compile_state.from_statement_ctx, + compile_state.select_statement, + statement, + params, + session, + load_options, + execution_options, + bind_arguments, + ) + return loading.instances(result, querycontext) + else: + return result + + +class BulkUDCompileState(ORMDMLState): + class default_update_options(Options): + _dml_strategy: DMLStrategyArgument = "auto" + _synchronize_session: SynchronizeSessionArgument = "auto" + _can_use_returning: bool = False + _is_delete_using: bool = False + _is_update_from: bool = False + _autoflush: bool = True + _subject_mapper: Optional[Mapper[Any]] = None + _resolved_values = EMPTY_DICT + _eval_condition = None + _matched_rows = None + _identity_token = None + _populate_existing: bool = False + + @classmethod + def can_use_returning( + cls, + dialect: Dialect, + mapper: Mapper[Any], + *, + is_multitable: bool = False, + is_update_from: bool = False, + is_delete_using: bool = False, + is_executemany: bool = False, + ) -> bool: + raise NotImplementedError() + + @classmethod + def orm_pre_session_exec( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + is_pre_event, + ): + ( + update_options, + execution_options, + ) = BulkUDCompileState.default_update_options.from_execution_options( + "_sa_orm_update_options", + { + "synchronize_session", + "autoflush", + "populate_existing", + "identity_token", + "is_delete_using", + "is_update_from", + "dml_strategy", + }, + execution_options, + statement._execution_options, + ) + bind_arguments["clause"] = statement + try: + plugin_subject = statement._propagate_attrs["plugin_subject"] + except KeyError: + assert False, "statement had 'orm' plugin but no plugin_subject" + else: + if plugin_subject: + bind_arguments["mapper"] = plugin_subject.mapper + update_options += {"_subject_mapper": plugin_subject.mapper} + + if "parententity" not in statement.table._annotations: + update_options += {"_dml_strategy": "core_only"} + elif not isinstance(params, list): + if update_options._dml_strategy == "auto": + update_options += {"_dml_strategy": "orm"} + elif update_options._dml_strategy == "bulk": + raise sa_exc.InvalidRequestError( + 'Can\'t use "bulk" ORM insert strategy without ' + "passing separate parameters" + ) + else: + if update_options._dml_strategy == "auto": + update_options += {"_dml_strategy": "bulk"} + + sync = update_options._synchronize_session + if sync is not None: + if sync not in ("auto", "evaluate", "fetch", False): + raise sa_exc.ArgumentError( + "Valid strategies for session synchronization " + "are 'auto', 'evaluate', 'fetch', False" + ) + if update_options._dml_strategy == "bulk" and sync == "fetch": + raise sa_exc.InvalidRequestError( + "The 'fetch' synchronization strategy is not available " + "for 'bulk' ORM updates (i.e. multiple parameter sets)" + ) + + if not is_pre_event: + if update_options._autoflush: + session._autoflush() + + if update_options._dml_strategy == "orm": + if update_options._synchronize_session == "auto": + update_options = cls._do_pre_synchronize_auto( + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ) + elif update_options._synchronize_session == "evaluate": + update_options = cls._do_pre_synchronize_evaluate( + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ) + elif update_options._synchronize_session == "fetch": + update_options = cls._do_pre_synchronize_fetch( + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ) + elif update_options._dml_strategy == "bulk": + if update_options._synchronize_session == "auto": + update_options += {"_synchronize_session": "evaluate"} + + # indicators from the "pre exec" step that are then + # added to the DML statement, which will also be part of the cache + # key. The compile level create_for_statement() method will then + # consume these at compiler time. + statement = statement._annotate( + { + "synchronize_session": update_options._synchronize_session, + "is_delete_using": update_options._is_delete_using, + "is_update_from": update_options._is_update_from, + "dml_strategy": update_options._dml_strategy, + "can_use_returning": update_options._can_use_returning, + } + ) + + return ( + statement, + util.immutabledict(execution_options).union( + {"_sa_orm_update_options": update_options} + ), + ) + + @classmethod + def orm_setup_cursor_result( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + result, + ): + # this stage of the execution is called after the + # do_orm_execute event hook. meaning for an extension like + # horizontal sharding, this step happens *within* the horizontal + # sharding event handler which calls session.execute() re-entrantly + # and will occur for each backend individually. + # the sharding extension then returns its own merged result from the + # individual ones we return here. + + update_options = execution_options["_sa_orm_update_options"] + if update_options._dml_strategy == "orm": + if update_options._synchronize_session == "evaluate": + cls._do_post_synchronize_evaluate( + session, statement, result, update_options + ) + elif update_options._synchronize_session == "fetch": + cls._do_post_synchronize_fetch( + session, statement, result, update_options + ) + elif update_options._dml_strategy == "bulk": + if update_options._synchronize_session == "evaluate": + cls._do_post_synchronize_bulk_evaluate( + session, params, result, update_options + ) + return result + + return cls._return_orm_returning( + session, + statement, + params, + execution_options, + bind_arguments, + result, + ) + + @classmethod + def _adjust_for_extra_criteria(cls, global_attributes, ext_info): + """Apply extra criteria filtering. + + For all distinct single-table-inheritance mappers represented in the + table being updated or deleted, produce additional WHERE criteria such + that only the appropriate subtypes are selected from the total results. + + Additionally, add WHERE criteria originating from LoaderCriteriaOptions + collected from the statement. + + """ + + return_crit = () + + adapter = ext_info._adapter if ext_info.is_aliased_class else None + + if ( + "additional_entity_criteria", + ext_info.mapper, + ) in global_attributes: + return_crit += tuple( + ae._resolve_where_criteria(ext_info) + for ae in global_attributes[ + ("additional_entity_criteria", ext_info.mapper) + ] + if ae.include_aliases or ae.entity is ext_info + ) + + if ext_info.mapper._single_table_criterion is not None: + return_crit += (ext_info.mapper._single_table_criterion,) + + if adapter: + return_crit = tuple(adapter.traverse(crit) for crit in return_crit) + + return return_crit + + @classmethod + def _interpret_returning_rows(cls, result, mapper, rows): + """return rows that indicate PK cols in mapper.primary_key position + for RETURNING rows. + + Prior to 2.0.36, this method seemed to be written for some kind of + inheritance scenario but the scenario was unused for actual joined + inheritance, and the function instead seemed to perform some kind of + partial translation that would remove non-PK cols if the PK cols + happened to be first in the row, but not otherwise. The joined + inheritance walk feature here seems to have never been used as it was + always skipped by the "local_table" check. + + As of 2.0.36 the function strips away non-PK cols and provides the + PK cols for the table in mapper PK order. + + """ + + try: + if mapper.local_table is not mapper.base_mapper.local_table: + # TODO: dive more into how a local table PK is used for fetch + # sync, not clear if this is correct as it depends on the + # downstream routine to fetch rows using + # local_table.primary_key order + pk_keys = result._tuple_getter(mapper.local_table.primary_key) + else: + pk_keys = result._tuple_getter(mapper.primary_key) + except KeyError: + # can't use these rows, they don't have PK cols in them + # this is an unusual case where the user would have used + # .return_defaults() + return [] + + return [pk_keys(row) for row in rows] + + @classmethod + def _get_matched_objects_on_criteria(cls, update_options, states): + mapper = update_options._subject_mapper + eval_condition = update_options._eval_condition + + raw_data = [ + (state.obj(), state, state.dict) + for state in states + if state.mapper.isa(mapper) and not state.expired + ] + + identity_token = update_options._identity_token + if identity_token is not None: + raw_data = [ + (obj, state, dict_) + for obj, state, dict_ in raw_data + if state.identity_token == identity_token + ] + + result = [] + for obj, state, dict_ in raw_data: + evaled_condition = eval_condition(obj) + + # caution: don't use "in ()" or == here, _EXPIRE_OBJECT + # evaluates as True for all comparisons + if ( + evaled_condition is True + or evaled_condition is evaluator._EXPIRED_OBJECT + ): + result.append( + ( + obj, + state, + dict_, + evaled_condition is evaluator._EXPIRED_OBJECT, + ) + ) + return result + + @classmethod + def _eval_condition_from_statement(cls, update_options, statement): + mapper = update_options._subject_mapper + target_cls = mapper.class_ + + evaluator_compiler = evaluator._EvaluatorCompiler(target_cls) + crit = () + if statement._where_criteria: + crit += statement._where_criteria + + global_attributes = {} + for opt in statement._with_options: + if opt._is_criteria_option: + opt.get_global_criteria(global_attributes) + + if global_attributes: + crit += cls._adjust_for_extra_criteria(global_attributes, mapper) + + if crit: + eval_condition = evaluator_compiler.process(*crit) + else: + # workaround for mypy https://github.com/python/mypy/issues/14027 + def _eval_condition(obj): + return True + + eval_condition = _eval_condition + + return eval_condition + + @classmethod + def _do_pre_synchronize_auto( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ): + """setup auto sync strategy + + + "auto" checks if we can use "evaluate" first, then falls back + to "fetch" + + evaluate is vastly more efficient for the common case + where session is empty, only has a few objects, and the UPDATE + statement can potentially match thousands/millions of rows. + + OTOH more complex criteria that fails to work with "evaluate" + we would hope usually correlates with fewer net rows. + + """ + + try: + eval_condition = cls._eval_condition_from_statement( + update_options, statement + ) + + except evaluator.UnevaluatableError: + pass + else: + return update_options + { + "_eval_condition": eval_condition, + "_synchronize_session": "evaluate", + } + + update_options += {"_synchronize_session": "fetch"} + return cls._do_pre_synchronize_fetch( + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ) + + @classmethod + def _do_pre_synchronize_evaluate( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ): + try: + eval_condition = cls._eval_condition_from_statement( + update_options, statement + ) + + except evaluator.UnevaluatableError as err: + raise sa_exc.InvalidRequestError( + 'Could not evaluate current criteria in Python: "%s". ' + "Specify 'fetch' or False for the " + "synchronize_session execution option." % err + ) from err + + return update_options + { + "_eval_condition": eval_condition, + } + + @classmethod + def _get_resolved_values(cls, mapper, statement): + if statement._multi_values: + return [] + elif statement._ordered_values: + return list(statement._ordered_values) + elif statement._values: + return list(statement._values.items()) + else: + return [] + + @classmethod + def _resolved_keys_as_propnames(cls, mapper, resolved_values): + values = [] + for k, v in resolved_values: + if mapper and isinstance(k, expression.ColumnElement): + try: + attr = mapper._columntoproperty[k] + except orm_exc.UnmappedColumnError: + pass + else: + values.append((attr.key, v)) + else: + raise sa_exc.InvalidRequestError( + "Attribute name not found, can't be " + "synchronized back to objects: %r" % k + ) + return values + + @classmethod + def _do_pre_synchronize_fetch( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + update_options, + ): + mapper = update_options._subject_mapper + + select_stmt = ( + select(*(mapper.primary_key + (mapper.select_identity_token,))) + .select_from(mapper) + .options(*statement._with_options) + ) + select_stmt._where_criteria = statement._where_criteria + + # conditionally run the SELECT statement for pre-fetch, testing the + # "bind" for if we can use RETURNING or not using the do_orm_execute + # event. If RETURNING is available, the do_orm_execute event + # will cancel the SELECT from being actually run. + # + # The way this is organized seems strange, why don't we just + # call can_use_returning() before invoking the statement and get + # answer?, why does this go through the whole execute phase using an + # event? Answer: because we are integrating with extensions such + # as the horizontal sharding extension that "multiplexes" an individual + # statement run through multiple engines, and it uses + # do_orm_execute() to do that. + + can_use_returning = None + + def skip_for_returning(orm_context: ORMExecuteState) -> Any: + bind = orm_context.session.get_bind(**orm_context.bind_arguments) + nonlocal can_use_returning + + per_bind_result = cls.can_use_returning( + bind.dialect, + mapper, + is_update_from=update_options._is_update_from, + is_delete_using=update_options._is_delete_using, + is_executemany=orm_context.is_executemany, + ) + + if can_use_returning is not None: + if can_use_returning != per_bind_result: + raise sa_exc.InvalidRequestError( + "For synchronize_session='fetch', can't mix multiple " + "backends where some support RETURNING and others " + "don't" + ) + elif orm_context.is_executemany and not per_bind_result: + raise sa_exc.InvalidRequestError( + "For synchronize_session='fetch', can't use multiple " + "parameter sets in ORM mode, which this backend does not " + "support with RETURNING" + ) + else: + can_use_returning = per_bind_result + + if per_bind_result: + return _result.null_result() + else: + return None + + result = session.execute( + select_stmt, + params, + execution_options=execution_options, + bind_arguments=bind_arguments, + _add_event=skip_for_returning, + ) + matched_rows = result.fetchall() + + return update_options + { + "_matched_rows": matched_rows, + "_can_use_returning": can_use_returning, + } + + +@CompileState.plugin_for("orm", "insert") +class BulkORMInsert(ORMDMLState, InsertDMLState): + class default_insert_options(Options): + _dml_strategy: DMLStrategyArgument = "auto" + _render_nulls: bool = False + _return_defaults: bool = False + _subject_mapper: Optional[Mapper[Any]] = None + _autoflush: bool = True + _populate_existing: bool = False + + select_statement: Optional[FromStatement] = None + + @classmethod + def orm_pre_session_exec( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + is_pre_event, + ): + ( + insert_options, + execution_options, + ) = BulkORMInsert.default_insert_options.from_execution_options( + "_sa_orm_insert_options", + {"dml_strategy", "autoflush", "populate_existing", "render_nulls"}, + execution_options, + statement._execution_options, + ) + bind_arguments["clause"] = statement + try: + plugin_subject = statement._propagate_attrs["plugin_subject"] + except KeyError: + assert False, "statement had 'orm' plugin but no plugin_subject" + else: + if plugin_subject: + bind_arguments["mapper"] = plugin_subject.mapper + insert_options += {"_subject_mapper": plugin_subject.mapper} + + if not params: + if insert_options._dml_strategy == "auto": + insert_options += {"_dml_strategy": "orm"} + elif insert_options._dml_strategy == "bulk": + raise sa_exc.InvalidRequestError( + 'Can\'t use "bulk" ORM insert strategy without ' + "passing separate parameters" + ) + else: + if insert_options._dml_strategy == "auto": + insert_options += {"_dml_strategy": "bulk"} + + if insert_options._dml_strategy != "raw": + # for ORM object loading, like ORMContext, we have to disable + # result set adapt_to_context, because we will be generating a + # new statement with specific columns that's cached inside of + # an ORMFromStatementCompileState, which we will reuse for + # each result. + if not execution_options: + execution_options = context._orm_load_exec_options + else: + execution_options = execution_options.union( + context._orm_load_exec_options + ) + + if not is_pre_event and insert_options._autoflush: + session._autoflush() + + statement = statement._annotate( + {"dml_strategy": insert_options._dml_strategy} + ) + + return ( + statement, + util.immutabledict(execution_options).union( + {"_sa_orm_insert_options": insert_options} + ), + ) + + @classmethod + def orm_execute_statement( + cls, + session: Session, + statement: dml.Insert, + params: _CoreAnyExecuteParams, + execution_options: OrmExecuteOptionsParameter, + bind_arguments: _BindArguments, + conn: Connection, + ) -> _result.Result: + insert_options = execution_options.get( + "_sa_orm_insert_options", cls.default_insert_options + ) + + if insert_options._dml_strategy not in ( + "raw", + "bulk", + "orm", + "auto", + ): + raise sa_exc.ArgumentError( + "Valid strategies for ORM insert strategy " + "are 'raw', 'orm', 'bulk', 'auto" + ) + + result: _result.Result[Any] + + if insert_options._dml_strategy == "raw": + result = conn.execute( + statement, params or {}, execution_options=execution_options + ) + return result + + if insert_options._dml_strategy == "bulk": + mapper = insert_options._subject_mapper + + if ( + statement._post_values_clause is not None + and mapper._multiple_persistence_tables + ): + raise sa_exc.InvalidRequestError( + "bulk INSERT with a 'post values' clause " + "(typically upsert) not supported for multi-table " + f"mapper {mapper}" + ) + + assert mapper is not None + assert session._transaction is not None + result = _bulk_insert( + mapper, + cast( + "Iterable[Dict[str, Any]]", + [params] if isinstance(params, dict) else params, + ), + session._transaction, + isstates=False, + return_defaults=insert_options._return_defaults, + render_nulls=insert_options._render_nulls, + use_orm_insert_stmt=statement, + execution_options=execution_options, + ) + elif insert_options._dml_strategy == "orm": + result = conn.execute( + statement, params or {}, execution_options=execution_options + ) + else: + raise AssertionError() + + if not bool(statement._returning): + return result + + if insert_options._populate_existing: + load_options = execution_options.get( + "_sa_orm_load_options", QueryContext.default_load_options + ) + load_options += {"_populate_existing": True} + execution_options = execution_options.union( + {"_sa_orm_load_options": load_options} + ) + + return cls._return_orm_returning( + session, + statement, + params, + execution_options, + bind_arguments, + result, + ) + + @classmethod + def create_for_statement(cls, statement, compiler, **kw) -> BulkORMInsert: + self = cast( + BulkORMInsert, + super().create_for_statement(statement, compiler, **kw), + ) + + if compiler is not None: + toplevel = not compiler.stack + else: + toplevel = True + if not toplevel: + return self + + mapper = statement._propagate_attrs["plugin_subject"] + dml_strategy = statement._annotations.get("dml_strategy", "raw") + if dml_strategy == "bulk": + self._setup_for_bulk_insert(compiler) + elif dml_strategy == "orm": + self._setup_for_orm_insert(compiler, mapper) + + return self + + @classmethod + def _resolved_keys_as_col_keys(cls, mapper, resolved_value_dict): + return { + col.key if col is not None else k: v + for col, k, v in ( + (mapper.c.get(k), k, v) for k, v in resolved_value_dict.items() + ) + } + + def _setup_for_orm_insert(self, compiler, mapper): + statement = orm_level_statement = cast(dml.Insert, self.statement) + + statement = self._setup_orm_returning( + compiler, + orm_level_statement, + statement, + dml_mapper=mapper, + use_supplemental_cols=False, + ) + self.statement = statement + + def _setup_for_bulk_insert(self, compiler): + """establish an INSERT statement within the context of + bulk insert. + + This method will be within the "conn.execute()" call that is invoked + by persistence._emit_insert_statement(). + + """ + statement = orm_level_statement = cast(dml.Insert, self.statement) + an = statement._annotations + + emit_insert_table, emit_insert_mapper = ( + an["_emit_insert_table"], + an["_emit_insert_mapper"], + ) + + statement = statement._clone() + + statement.table = emit_insert_table + if self._dict_parameters: + self._dict_parameters = { + col: val + for col, val in self._dict_parameters.items() + if col.table is emit_insert_table + } + + statement = self._setup_orm_returning( + compiler, + orm_level_statement, + statement, + dml_mapper=emit_insert_mapper, + use_supplemental_cols=True, + ) + + if ( + self.from_statement_ctx is not None + and self.from_statement_ctx.compile_options._is_star + ): + raise sa_exc.CompileError( + "Can't use RETURNING * with bulk ORM INSERT. " + "Please use a different INSERT form, such as INSERT..VALUES " + "or INSERT with a Core Connection" + ) + + self.statement = statement + + +@CompileState.plugin_for("orm", "update") +class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): + @classmethod + def create_for_statement(cls, statement, compiler, **kw): + self = cls.__new__(cls) + + dml_strategy = statement._annotations.get( + "dml_strategy", "unspecified" + ) + + toplevel = not compiler.stack + + if toplevel and dml_strategy == "bulk": + self._setup_for_bulk_update(statement, compiler) + elif ( + dml_strategy == "core_only" + or dml_strategy == "unspecified" + and "parententity" not in statement.table._annotations + ): + UpdateDMLState.__init__(self, statement, compiler, **kw) + elif not toplevel or dml_strategy in ("orm", "unspecified"): + self._setup_for_orm_update(statement, compiler) + + return self + + def _setup_for_orm_update(self, statement, compiler, **kw): + orm_level_statement = statement + + toplevel = not compiler.stack + + ext_info = statement.table._annotations["parententity"] + + self.mapper = mapper = ext_info.mapper + + self._resolved_values = self._get_resolved_values(mapper, statement) + + self._init_global_attributes( + statement, + compiler, + toplevel=toplevel, + process_criteria_for_toplevel=toplevel, + ) + + if statement._values: + self._resolved_values = dict(self._resolved_values) + + new_stmt = statement._clone() + + if new_stmt.table._annotations["parententity"] is mapper: + new_stmt.table = mapper.local_table + + # note if the statement has _multi_values, these + # are passed through to the new statement, which will then raise + # InvalidRequestError because UPDATE doesn't support multi_values + # right now. + if statement._ordered_values: + new_stmt._ordered_values = self._resolved_values + elif statement._values: + new_stmt._values = self._resolved_values + + new_crit = self._adjust_for_extra_criteria( + self.global_attributes, mapper + ) + if new_crit: + new_stmt = new_stmt.where(*new_crit) + + # if we are against a lambda statement we might not be the + # topmost object that received per-execute annotations + + # do this first as we need to determine if there is + # UPDATE..FROM + + UpdateDMLState.__init__(self, new_stmt, compiler, **kw) + + use_supplemental_cols = False + + if not toplevel: + synchronize_session = None + else: + synchronize_session = compiler._annotations.get( + "synchronize_session", None + ) + can_use_returning = compiler._annotations.get( + "can_use_returning", None + ) + if can_use_returning is not False: + # even though pre_exec has determined basic + # can_use_returning for the dialect, if we are to use + # RETURNING we need to run can_use_returning() at this level + # unconditionally because is_delete_using was not known + # at the pre_exec level + can_use_returning = ( + synchronize_session == "fetch" + and self.can_use_returning( + compiler.dialect, mapper, is_multitable=self.is_multitable + ) + ) + + if synchronize_session == "fetch" and can_use_returning: + use_supplemental_cols = True + + # NOTE: we might want to RETURNING the actual columns to be + # synchronized also. however this is complicated and difficult + # to align against the behavior of "evaluate". Additionally, + # in a large number (if not the majority) of cases, we have the + # "evaluate" answer, usually a fixed value, in memory already and + # there's no need to re-fetch the same value + # over and over again. so perhaps if it could be RETURNING just + # the elements that were based on a SQL expression and not + # a constant. For now it doesn't quite seem worth it + new_stmt = new_stmt.return_defaults(*new_stmt.table.primary_key) + + if toplevel: + new_stmt = self._setup_orm_returning( + compiler, + orm_level_statement, + new_stmt, + dml_mapper=mapper, + use_supplemental_cols=use_supplemental_cols, + ) + + self.statement = new_stmt + + def _setup_for_bulk_update(self, statement, compiler, **kw): + """establish an UPDATE statement within the context of + bulk insert. + + This method will be within the "conn.execute()" call that is invoked + by persistence._emit_update_statement(). + + """ + statement = cast(dml.Update, statement) + an = statement._annotations + + emit_update_table, _ = ( + an["_emit_update_table"], + an["_emit_update_mapper"], + ) + + statement = statement._clone() + statement.table = emit_update_table + + UpdateDMLState.__init__(self, statement, compiler, **kw) + + if self._ordered_values: + raise sa_exc.InvalidRequestError( + "bulk ORM UPDATE does not support ordered_values() for " + "custom UPDATE statements with bulk parameter sets. Use a " + "non-bulk UPDATE statement or use values()." + ) + + if self._dict_parameters: + self._dict_parameters = { + col: val + for col, val in self._dict_parameters.items() + if col.table is emit_update_table + } + self.statement = statement + + @classmethod + def orm_execute_statement( + cls, + session: Session, + statement: dml.Update, + params: _CoreAnyExecuteParams, + execution_options: OrmExecuteOptionsParameter, + bind_arguments: _BindArguments, + conn: Connection, + ) -> _result.Result: + + update_options = execution_options.get( + "_sa_orm_update_options", cls.default_update_options + ) + + if update_options._populate_existing: + load_options = execution_options.get( + "_sa_orm_load_options", QueryContext.default_load_options + ) + load_options += {"_populate_existing": True} + execution_options = execution_options.union( + {"_sa_orm_load_options": load_options} + ) + + if update_options._dml_strategy not in ( + "orm", + "auto", + "bulk", + "core_only", + ): + raise sa_exc.ArgumentError( + "Valid strategies for ORM UPDATE strategy " + "are 'orm', 'auto', 'bulk', 'core_only'" + ) + + result: _result.Result[Any] + + if update_options._dml_strategy == "bulk": + enable_check_rowcount = not statement._where_criteria + + assert update_options._synchronize_session != "fetch" + + if ( + statement._where_criteria + and update_options._synchronize_session == "evaluate" + ): + raise sa_exc.InvalidRequestError( + "bulk synchronize of persistent objects not supported " + "when using bulk update with additional WHERE " + "criteria right now. add synchronize_session=None " + "execution option to bypass synchronize of persistent " + "objects." + ) + mapper = update_options._subject_mapper + assert mapper is not None + assert session._transaction is not None + result = _bulk_update( + mapper, + cast( + "Iterable[Dict[str, Any]]", + [params] if isinstance(params, dict) else params, + ), + session._transaction, + isstates=False, + update_changed_only=False, + use_orm_update_stmt=statement, + enable_check_rowcount=enable_check_rowcount, + ) + return cls.orm_setup_cursor_result( + session, + statement, + params, + execution_options, + bind_arguments, + result, + ) + else: + return super().orm_execute_statement( + session, + statement, + params, + execution_options, + bind_arguments, + conn, + ) + + @classmethod + def can_use_returning( + cls, + dialect: Dialect, + mapper: Mapper[Any], + *, + is_multitable: bool = False, + is_update_from: bool = False, + is_delete_using: bool = False, + is_executemany: bool = False, + ) -> bool: + # normal answer for "should we use RETURNING" at all. + normal_answer = ( + dialect.update_returning and mapper.local_table.implicit_returning + ) + if not normal_answer: + return False + + if is_executemany: + return dialect.update_executemany_returning + + # these workarounds are currently hypothetical for UPDATE, + # unlike DELETE where they impact MariaDB + if is_update_from: + return dialect.update_returning_multifrom + + elif is_multitable and not dialect.update_returning_multifrom: + raise sa_exc.CompileError( + f'Dialect "{dialect.name}" does not support RETURNING ' + "with UPDATE..FROM; for synchronize_session='fetch', " + "please add the additional execution option " + "'is_update_from=True' to the statement to indicate that " + "a separate SELECT should be used for this backend." + ) + + return True + + @classmethod + def _do_post_synchronize_bulk_evaluate( + cls, session, params, result, update_options + ): + if not params: + return + + mapper = update_options._subject_mapper + pk_keys = [prop.key for prop in mapper._identity_key_props] + + identity_map = session.identity_map + + for param in params: + identity_key = mapper.identity_key_from_primary_key( + (param[key] for key in pk_keys), + update_options._identity_token, + ) + state = identity_map.fast_get_state(identity_key) + if not state: + continue + + evaluated_keys = set(param).difference(pk_keys) + + dict_ = state.dict + # only evaluate unmodified attributes + to_evaluate = state.unmodified.intersection(evaluated_keys) + for key in to_evaluate: + if key in dict_: + dict_[key] = param[key] + + state.manager.dispatch.refresh(state, None, to_evaluate) + + state._commit(dict_, list(to_evaluate)) + + # attributes that were formerly modified instead get expired. + # this only gets hit if the session had pending changes + # and autoflush were set to False. + to_expire = evaluated_keys.intersection(dict_).difference( + to_evaluate + ) + if to_expire: + state._expire_attributes(dict_, to_expire) + + @classmethod + def _do_post_synchronize_evaluate( + cls, session, statement, result, update_options + ): + matched_objects = cls._get_matched_objects_on_criteria( + update_options, + session.identity_map.all_states(), + ) + + cls._apply_update_set_values_to_objects( + session, + update_options, + statement, + result.context.compiled_parameters[0], + [(obj, state, dict_) for obj, state, dict_, _ in matched_objects], + result.prefetch_cols(), + result.postfetch_cols(), + ) + + @classmethod + def _do_post_synchronize_fetch( + cls, session, statement, result, update_options + ): + target_mapper = update_options._subject_mapper + + returned_defaults_rows = result.returned_defaults_rows + if returned_defaults_rows: + pk_rows = cls._interpret_returning_rows( + result, target_mapper, returned_defaults_rows + ) + matched_rows = [ + tuple(row) + (update_options._identity_token,) + for row in pk_rows + ] + else: + matched_rows = update_options._matched_rows + + objs = [ + session.identity_map[identity_key] + for identity_key in [ + target_mapper.identity_key_from_primary_key( + list(primary_key), + identity_token=identity_token, + ) + for primary_key, identity_token in [ + (row[0:-1], row[-1]) for row in matched_rows + ] + if update_options._identity_token is None + or identity_token == update_options._identity_token + ] + if identity_key in session.identity_map + ] + + if not objs: + return + + cls._apply_update_set_values_to_objects( + session, + update_options, + statement, + result.context.compiled_parameters[0], + [ + ( + obj, + attributes.instance_state(obj), + attributes.instance_dict(obj), + ) + for obj in objs + ], + result.prefetch_cols(), + result.postfetch_cols(), + ) + + @classmethod + def _apply_update_set_values_to_objects( + cls, + session, + update_options, + statement, + effective_params, + matched_objects, + prefetch_cols, + postfetch_cols, + ): + """apply values to objects derived from an update statement, e.g. + UPDATE..SET + + """ + + mapper = update_options._subject_mapper + target_cls = mapper.class_ + evaluator_compiler = evaluator._EvaluatorCompiler(target_cls) + resolved_values = cls._get_resolved_values(mapper, statement) + resolved_keys_as_propnames = cls._resolved_keys_as_propnames( + mapper, resolved_values + ) + value_evaluators = {} + for key, value in resolved_keys_as_propnames: + try: + _evaluator = evaluator_compiler.process( + coercions.expect(roles.ExpressionElementRole, value) + ) + except evaluator.UnevaluatableError: + pass + else: + value_evaluators[key] = _evaluator + + evaluated_keys = list(value_evaluators.keys()) + attrib = {k for k, v in resolved_keys_as_propnames} + + states = set() + + to_prefetch = { + c + for c in prefetch_cols + if c.key in effective_params + and c in mapper._columntoproperty + and c.key not in evaluated_keys + } + to_expire = { + mapper._columntoproperty[c].key + for c in postfetch_cols + if c in mapper._columntoproperty + }.difference(evaluated_keys) + + prefetch_transfer = [ + (mapper._columntoproperty[c].key, c.key) for c in to_prefetch + ] + + for obj, state, dict_ in matched_objects: + + dict_.update( + { + col_to_prop: effective_params[c_key] + for col_to_prop, c_key in prefetch_transfer + } + ) + + state._expire_attributes(state.dict, to_expire) + + to_evaluate = state.unmodified.intersection(evaluated_keys) + + for key in to_evaluate: + if key in dict_: + # only run eval for attributes that are present. + dict_[key] = value_evaluators[key](obj) + + state.manager.dispatch.refresh(state, None, to_evaluate) + + state._commit(dict_, list(to_evaluate)) + + # attributes that were formerly modified instead get expired. + # this only gets hit if the session had pending changes + # and autoflush were set to False. + to_expire = attrib.intersection(dict_).difference(to_evaluate) + if to_expire: + state._expire_attributes(dict_, to_expire) + + states.add(state) + session._register_altered(states) + + +@CompileState.plugin_for("orm", "delete") +class BulkORMDelete(BulkUDCompileState, DeleteDMLState): + @classmethod + def create_for_statement(cls, statement, compiler, **kw): + self = cls.__new__(cls) + + dml_strategy = statement._annotations.get( + "dml_strategy", "unspecified" + ) + + if ( + dml_strategy == "core_only" + or dml_strategy == "unspecified" + and "parententity" not in statement.table._annotations + ): + DeleteDMLState.__init__(self, statement, compiler, **kw) + return self + + toplevel = not compiler.stack + + orm_level_statement = statement + + ext_info = statement.table._annotations["parententity"] + self.mapper = mapper = ext_info.mapper + + self._init_global_attributes( + statement, + compiler, + toplevel=toplevel, + process_criteria_for_toplevel=toplevel, + ) + + new_stmt = statement._clone() + + if new_stmt.table._annotations["parententity"] is mapper: + new_stmt.table = mapper.local_table + + new_crit = cls._adjust_for_extra_criteria( + self.global_attributes, mapper + ) + if new_crit: + new_stmt = new_stmt.where(*new_crit) + + # do this first as we need to determine if there is + # DELETE..FROM + DeleteDMLState.__init__(self, new_stmt, compiler, **kw) + + use_supplemental_cols = False + + if not toplevel: + synchronize_session = None + else: + synchronize_session = compiler._annotations.get( + "synchronize_session", None + ) + can_use_returning = compiler._annotations.get( + "can_use_returning", None + ) + if can_use_returning is not False: + # even though pre_exec has determined basic + # can_use_returning for the dialect, if we are to use + # RETURNING we need to run can_use_returning() at this level + # unconditionally because is_delete_using was not known + # at the pre_exec level + can_use_returning = ( + synchronize_session == "fetch" + and self.can_use_returning( + compiler.dialect, + mapper, + is_multitable=self.is_multitable, + is_delete_using=compiler._annotations.get( + "is_delete_using", False + ), + ) + ) + + if can_use_returning: + use_supplemental_cols = True + + new_stmt = new_stmt.return_defaults(*new_stmt.table.primary_key) + + if toplevel: + new_stmt = self._setup_orm_returning( + compiler, + orm_level_statement, + new_stmt, + dml_mapper=mapper, + use_supplemental_cols=use_supplemental_cols, + ) + + self.statement = new_stmt + + return self + + @classmethod + def orm_execute_statement( + cls, + session: Session, + statement: dml.Delete, + params: _CoreAnyExecuteParams, + execution_options: OrmExecuteOptionsParameter, + bind_arguments: _BindArguments, + conn: Connection, + ) -> _result.Result: + update_options = execution_options.get( + "_sa_orm_update_options", cls.default_update_options + ) + + if update_options._dml_strategy == "bulk": + raise sa_exc.InvalidRequestError( + "Bulk ORM DELETE not supported right now. " + "Statement may be invoked at the " + "Core level using " + "session.connection().execute(stmt, parameters)" + ) + + if update_options._dml_strategy not in ("orm", "auto", "core_only"): + raise sa_exc.ArgumentError( + "Valid strategies for ORM DELETE strategy are 'orm', 'auto', " + "'core_only'" + ) + + return super().orm_execute_statement( + session, statement, params, execution_options, bind_arguments, conn + ) + + @classmethod + def can_use_returning( + cls, + dialect: Dialect, + mapper: Mapper[Any], + *, + is_multitable: bool = False, + is_update_from: bool = False, + is_delete_using: bool = False, + is_executemany: bool = False, + ) -> bool: + # normal answer for "should we use RETURNING" at all. + normal_answer = ( + dialect.delete_returning and mapper.local_table.implicit_returning + ) + if not normal_answer: + return False + + # now get into special workarounds because MariaDB supports + # DELETE...RETURNING but not DELETE...USING...RETURNING. + if is_delete_using: + # is_delete_using hint was passed. use + # additional dialect feature (True for PG, False for MariaDB) + return dialect.delete_returning_multifrom + + elif is_multitable and not dialect.delete_returning_multifrom: + # is_delete_using hint was not passed, but we determined + # at compile time that this is in fact a DELETE..USING. + # it's too late to continue since we did not pre-SELECT. + # raise that we need that hint up front. + + raise sa_exc.CompileError( + f'Dialect "{dialect.name}" does not support RETURNING ' + "with DELETE..USING; for synchronize_session='fetch', " + "please add the additional execution option " + "'is_delete_using=True' to the statement to indicate that " + "a separate SELECT should be used for this backend." + ) + + return True + + @classmethod + def _do_post_synchronize_evaluate( + cls, session, statement, result, update_options + ): + matched_objects = cls._get_matched_objects_on_criteria( + update_options, + session.identity_map.all_states(), + ) + + to_delete = [] + + for _, state, dict_, is_partially_expired in matched_objects: + if is_partially_expired: + state._expire(dict_, session.identity_map._modified) + else: + to_delete.append(state) + + if to_delete: + session._remove_newly_deleted(to_delete) + + @classmethod + def _do_post_synchronize_fetch( + cls, session, statement, result, update_options + ): + target_mapper = update_options._subject_mapper + + returned_defaults_rows = result.returned_defaults_rows + + if returned_defaults_rows: + pk_rows = cls._interpret_returning_rows( + result, target_mapper, returned_defaults_rows + ) + + matched_rows = [ + tuple(row) + (update_options._identity_token,) + for row in pk_rows + ] + else: + matched_rows = update_options._matched_rows + + for row in matched_rows: + primary_key = row[0:-1] + identity_token = row[-1] + + # TODO: inline this and call remove_newly_deleted + # once + identity_key = target_mapper.identity_key_from_primary_key( + list(primary_key), + identity_token=identity_token, + ) + if identity_key in session.identity_map: + session._remove_newly_deleted( + [ + attributes.instance_state( + session.identity_map[identity_key] + ) + ] + ) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/clsregistry.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/clsregistry.py new file mode 100644 index 0000000000000000000000000000000000000000..8807031fa45db93ece706ba6f203e7447a5073c5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/clsregistry.py @@ -0,0 +1,571 @@ +# orm/clsregistry.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Routines to handle the string class registry used by declarative. + +This system allows specification of classes and expressions used in +:func:`_orm.relationship` using strings. + +""" + +from __future__ import annotations + +import re +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import Generator +from typing import Iterable +from typing import List +from typing import Mapping +from typing import MutableMapping +from typing import NoReturn +from typing import Optional +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import attributes +from . import interfaces +from .descriptor_props import SynonymProperty +from .properties import ColumnProperty +from .util import class_mapper +from .. import exc +from .. import inspection +from .. import util +from ..sql.schema import _get_table_key +from ..util.typing import CallableReference + +if TYPE_CHECKING: + from .relationships import RelationshipProperty + from ..sql.schema import MetaData + from ..sql.schema import Table + +_T = TypeVar("_T", bound=Any) + +_ClsRegistryType = MutableMapping[str, Union[type, "ClsRegistryToken"]] + +# strong references to registries which we place in +# the _decl_class_registry, which is usually weak referencing. +# the internal registries here link to classes with weakrefs and remove +# themselves when all references to contained classes are removed. +_registries: Set[ClsRegistryToken] = set() + + +def add_class( + classname: str, cls: Type[_T], decl_class_registry: _ClsRegistryType +) -> None: + """Add a class to the _decl_class_registry associated with the + given declarative class. + + """ + if classname in decl_class_registry: + # class already exists. + existing = decl_class_registry[classname] + if not isinstance(existing, _MultipleClassMarker): + decl_class_registry[classname] = _MultipleClassMarker( + [cls, cast("Type[Any]", existing)] + ) + else: + decl_class_registry[classname] = cls + + try: + root_module = cast( + _ModuleMarker, decl_class_registry["_sa_module_registry"] + ) + except KeyError: + decl_class_registry["_sa_module_registry"] = root_module = ( + _ModuleMarker("_sa_module_registry", None) + ) + + tokens = cls.__module__.split(".") + + # build up a tree like this: + # modulename: myapp.snacks.nuts + # + # myapp->snack->nuts->(classes) + # snack->nuts->(classes) + # nuts->(classes) + # + # this allows partial token paths to be used. + while tokens: + token = tokens.pop(0) + module = root_module.get_module(token) + for token in tokens: + module = module.get_module(token) + + try: + module.add_class(classname, cls) + except AttributeError as ae: + if not isinstance(module, _ModuleMarker): + raise exc.InvalidRequestError( + f'name "{classname}" matches both a ' + "class name and a module name" + ) from ae + else: + raise + + +def remove_class( + classname: str, cls: Type[Any], decl_class_registry: _ClsRegistryType +) -> None: + if classname in decl_class_registry: + existing = decl_class_registry[classname] + if isinstance(existing, _MultipleClassMarker): + existing.remove_item(cls) + else: + del decl_class_registry[classname] + + try: + root_module = cast( + _ModuleMarker, decl_class_registry["_sa_module_registry"] + ) + except KeyError: + return + + tokens = cls.__module__.split(".") + + while tokens: + token = tokens.pop(0) + module = root_module.get_module(token) + for token in tokens: + module = module.get_module(token) + try: + module.remove_class(classname, cls) + except AttributeError: + if not isinstance(module, _ModuleMarker): + pass + else: + raise + + +def _key_is_empty( + key: str, + decl_class_registry: _ClsRegistryType, + test: Callable[[Any], bool], +) -> bool: + """test if a key is empty of a certain object. + + used for unit tests against the registry to see if garbage collection + is working. + + "test" is a callable that will be passed an object should return True + if the given object is the one we were looking for. + + We can't pass the actual object itself b.c. this is for testing garbage + collection; the caller will have to have removed references to the + object itself. + + """ + if key not in decl_class_registry: + return True + + thing = decl_class_registry[key] + if isinstance(thing, _MultipleClassMarker): + for sub_thing in thing.contents: + if test(sub_thing): + return False + else: + raise NotImplementedError("unknown codepath") + else: + return not test(thing) + + +class ClsRegistryToken: + """an object that can be in the registry._class_registry as a value.""" + + __slots__ = () + + +class _MultipleClassMarker(ClsRegistryToken): + """refers to multiple classes of the same name + within _decl_class_registry. + + """ + + __slots__ = "on_remove", "contents", "__weakref__" + + contents: Set[weakref.ref[Type[Any]]] + on_remove: CallableReference[Optional[Callable[[], None]]] + + def __init__( + self, + classes: Iterable[Type[Any]], + on_remove: Optional[Callable[[], None]] = None, + ): + self.on_remove = on_remove + self.contents = { + weakref.ref(item, self._remove_item) for item in classes + } + _registries.add(self) + + def remove_item(self, cls: Type[Any]) -> None: + self._remove_item(weakref.ref(cls)) + + def __iter__(self) -> Generator[Optional[Type[Any]], None, None]: + return (ref() for ref in self.contents) + + def attempt_get(self, path: List[str], key: str) -> Type[Any]: + if len(self.contents) > 1: + raise exc.InvalidRequestError( + 'Multiple classes found for path "%s" ' + "in the registry of this declarative " + "base. Please use a fully module-qualified path." + % (".".join(path + [key])) + ) + else: + ref = list(self.contents)[0] + cls = ref() + if cls is None: + raise NameError(key) + return cls + + def _remove_item(self, ref: weakref.ref[Type[Any]]) -> None: + self.contents.discard(ref) + if not self.contents: + _registries.discard(self) + if self.on_remove: + self.on_remove() + + def add_item(self, item: Type[Any]) -> None: + # protect against class registration race condition against + # asynchronous garbage collection calling _remove_item, + # [ticket:3208] and [ticket:10782] + modules = { + cls.__module__ + for cls in [ref() for ref in list(self.contents)] + if cls is not None + } + if item.__module__ in modules: + util.warn( + "This declarative base already contains a class with the " + "same class name and module name as %s.%s, and will " + "be replaced in the string-lookup table." + % (item.__module__, item.__name__) + ) + self.contents.add(weakref.ref(item, self._remove_item)) + + +class _ModuleMarker(ClsRegistryToken): + """Refers to a module name within + _decl_class_registry. + + """ + + __slots__ = "parent", "name", "contents", "mod_ns", "path", "__weakref__" + + parent: Optional[_ModuleMarker] + contents: Dict[str, Union[_ModuleMarker, _MultipleClassMarker]] + mod_ns: _ModNS + path: List[str] + + def __init__(self, name: str, parent: Optional[_ModuleMarker]): + self.parent = parent + self.name = name + self.contents = {} + self.mod_ns = _ModNS(self) + if self.parent: + self.path = self.parent.path + [self.name] + else: + self.path = [] + _registries.add(self) + + def __contains__(self, name: str) -> bool: + return name in self.contents + + def __getitem__(self, name: str) -> ClsRegistryToken: + return self.contents[name] + + def _remove_item(self, name: str) -> None: + self.contents.pop(name, None) + if not self.contents: + if self.parent is not None: + self.parent._remove_item(self.name) + _registries.discard(self) + + def resolve_attr(self, key: str) -> Union[_ModNS, Type[Any]]: + return self.mod_ns.__getattr__(key) + + def get_module(self, name: str) -> _ModuleMarker: + if name not in self.contents: + marker = _ModuleMarker(name, self) + self.contents[name] = marker + else: + marker = cast(_ModuleMarker, self.contents[name]) + return marker + + def add_class(self, name: str, cls: Type[Any]) -> None: + if name in self.contents: + existing = cast(_MultipleClassMarker, self.contents[name]) + try: + existing.add_item(cls) + except AttributeError as ae: + if not isinstance(existing, _MultipleClassMarker): + raise exc.InvalidRequestError( + f'name "{name}" matches both a ' + "class name and a module name" + ) from ae + else: + raise + else: + self.contents[name] = _MultipleClassMarker( + [cls], on_remove=lambda: self._remove_item(name) + ) + + def remove_class(self, name: str, cls: Type[Any]) -> None: + if name in self.contents: + existing = cast(_MultipleClassMarker, self.contents[name]) + existing.remove_item(cls) + + +class _ModNS: + __slots__ = ("__parent",) + + __parent: _ModuleMarker + + def __init__(self, parent: _ModuleMarker): + self.__parent = parent + + def __getattr__(self, key: str) -> Union[_ModNS, Type[Any]]: + try: + value = self.__parent.contents[key] + except KeyError: + pass + else: + if value is not None: + if isinstance(value, _ModuleMarker): + return value.mod_ns + else: + assert isinstance(value, _MultipleClassMarker) + return value.attempt_get(self.__parent.path, key) + raise NameError( + "Module %r has no mapped classes " + "registered under the name %r" % (self.__parent.name, key) + ) + + +class _GetColumns: + __slots__ = ("cls",) + + cls: Type[Any] + + def __init__(self, cls: Type[Any]): + self.cls = cls + + def __getattr__(self, key: str) -> Any: + mp = class_mapper(self.cls, configure=False) + if mp: + if key not in mp.all_orm_descriptors: + raise AttributeError( + "Class %r does not have a mapped column named %r" + % (self.cls, key) + ) + + desc = mp.all_orm_descriptors[key] + if desc.extension_type is interfaces.NotExtension.NOT_EXTENSION: + assert isinstance(desc, attributes.QueryableAttribute) + prop = desc.property + if isinstance(prop, SynonymProperty): + key = prop.name + elif not isinstance(prop, ColumnProperty): + raise exc.InvalidRequestError( + "Property %r is not an instance of" + " ColumnProperty (i.e. does not correspond" + " directly to a Column)." % key + ) + return getattr(self.cls, key) + + +inspection._inspects(_GetColumns)( + lambda target: inspection.inspect(target.cls) +) + + +class _GetTable: + __slots__ = "key", "metadata" + + key: str + metadata: MetaData + + def __init__(self, key: str, metadata: MetaData): + self.key = key + self.metadata = metadata + + def __getattr__(self, key: str) -> Table: + return self.metadata.tables[_get_table_key(key, self.key)] + + +def _determine_container(key: str, value: Any) -> _GetColumns: + if isinstance(value, _MultipleClassMarker): + value = value.attempt_get([], key) + return _GetColumns(value) + + +class _class_resolver: + __slots__ = ( + "cls", + "prop", + "arg", + "fallback", + "_dict", + "_resolvers", + "favor_tables", + ) + + cls: Type[Any] + prop: RelationshipProperty[Any] + fallback: Mapping[str, Any] + arg: str + favor_tables: bool + _resolvers: Tuple[Callable[[str], Any], ...] + + def __init__( + self, + cls: Type[Any], + prop: RelationshipProperty[Any], + fallback: Mapping[str, Any], + arg: str, + favor_tables: bool = False, + ): + self.cls = cls + self.prop = prop + self.arg = arg + self.fallback = fallback + self._dict = util.PopulateDict(self._access_cls) + self._resolvers = () + self.favor_tables = favor_tables + + def _access_cls(self, key: str) -> Any: + cls = self.cls + + manager = attributes.manager_of_class(cls) + decl_base = manager.registry + assert decl_base is not None + decl_class_registry = decl_base._class_registry + metadata = decl_base.metadata + + if self.favor_tables: + if key in metadata.tables: + return metadata.tables[key] + elif key in metadata._schemas: + return _GetTable(key, getattr(cls, "metadata", metadata)) + + if key in decl_class_registry: + return _determine_container(key, decl_class_registry[key]) + + if not self.favor_tables: + if key in metadata.tables: + return metadata.tables[key] + elif key in metadata._schemas: + return _GetTable(key, getattr(cls, "metadata", metadata)) + + if "_sa_module_registry" in decl_class_registry and key in cast( + _ModuleMarker, decl_class_registry["_sa_module_registry"] + ): + registry = cast( + _ModuleMarker, decl_class_registry["_sa_module_registry"] + ) + return registry.resolve_attr(key) + elif self._resolvers: + for resolv in self._resolvers: + value = resolv(key) + if value is not None: + return value + + return self.fallback[key] + + def _raise_for_name(self, name: str, err: Exception) -> NoReturn: + generic_match = re.match(r"(.+)\[(.+)\]", name) + + if generic_match: + clsarg = generic_match.group(2).strip("'") + raise exc.InvalidRequestError( + f"When initializing mapper {self.prop.parent}, " + f'expression "relationship({self.arg!r})" seems to be ' + "using a generic class as the argument to relationship(); " + "please state the generic argument " + "using an annotation, e.g. " + f'"{self.prop.key}: Mapped[{generic_match.group(1)}' + f"['{clsarg}']] = relationship()\"" + ) from err + else: + raise exc.InvalidRequestError( + "When initializing mapper %s, expression %r failed to " + "locate a name (%r). If this is a class name, consider " + "adding this relationship() to the %r class after " + "both dependent classes have been defined." + % (self.prop.parent, self.arg, name, self.cls) + ) from err + + def _resolve_name(self) -> Union[Table, Type[Any], _ModNS]: + name = self.arg + d = self._dict + rval = None + try: + for token in name.split("."): + if rval is None: + rval = d[token] + else: + rval = getattr(rval, token) + except KeyError as err: + self._raise_for_name(name, err) + except NameError as n: + self._raise_for_name(n.args[0], n) + else: + if isinstance(rval, _GetColumns): + return rval.cls + else: + if TYPE_CHECKING: + assert isinstance(rval, (type, Table, _ModNS)) + return rval + + def __call__(self) -> Any: + try: + x = eval(self.arg, globals(), self._dict) + + if isinstance(x, _GetColumns): + return x.cls + else: + return x + except NameError as n: + self._raise_for_name(n.args[0], n) + + +_fallback_dict: Mapping[str, Any] = None # type: ignore + + +def _resolver(cls: Type[Any], prop: RelationshipProperty[Any]) -> Tuple[ + Callable[[str], Callable[[], Union[Type[Any], Table, _ModNS]]], + Callable[[str, bool], _class_resolver], +]: + global _fallback_dict + + if _fallback_dict is None: + import sqlalchemy + from . import foreign + from . import remote + + _fallback_dict = util.immutabledict(sqlalchemy.__dict__).union( + {"foreign": foreign, "remote": remote} + ) + + def resolve_arg(arg: str, favor_tables: bool = False) -> _class_resolver: + return _class_resolver( + cls, prop, _fallback_dict, arg, favor_tables=favor_tables + ) + + def resolve_name( + arg: str, + ) -> Callable[[], Union[Type[Any], Table, _ModNS]]: + return _class_resolver(cls, prop, _fallback_dict, arg)._resolve_name + + return resolve_name, resolve_arg diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/collections.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/collections.py new file mode 100644 index 0000000000000000000000000000000000000000..bccff6d70c1a3a113f43929c2a16c2790a25b000 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/collections.py @@ -0,0 +1,1627 @@ +# orm/collections.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: allow-untyped-defs, allow-untyped-calls + +"""Support for collections of mapped entities. + +The collections package supplies the machinery used to inform the ORM of +collection membership changes. An instrumentation via decoration approach is +used, allowing arbitrary types (including built-ins) to be used as entity +collections without requiring inheritance from a base class. + +Instrumentation decoration relays membership change events to the +:class:`.CollectionAttributeImpl` that is currently managing the collection. +The decorators observe function call arguments and return values, tracking +entities entering or leaving the collection. Two decorator approaches are +provided. One is a bundle of generic decorators that map function arguments +and return values to events:: + + from sqlalchemy.orm.collections import collection + + + class MyClass: + # ... + + @collection.adds(1) + def store(self, item): + self.data.append(item) + + @collection.removes_return() + def pop(self): + return self.data.pop() + +The second approach is a bundle of targeted decorators that wrap appropriate +append and remove notifiers around the mutation methods present in the +standard Python ``list``, ``set`` and ``dict`` interfaces. These could be +specified in terms of generic decorator recipes, but are instead hand-tooled +for increased efficiency. The targeted decorators occasionally implement +adapter-like behavior, such as mapping bulk-set methods (``extend``, +``update``, ``__setslice__``, etc.) into the series of atomic mutation events +that the ORM requires. + +The targeted decorators are used internally for automatic instrumentation of +entity collection classes. Every collection class goes through a +transformation process roughly like so: + +1. If the class is a built-in, substitute a trivial sub-class +2. Is this class already instrumented? +3. Add in generic decorators +4. Sniff out the collection interface through duck-typing +5. Add targeted decoration to any undecorated interface method + +This process modifies the class at runtime, decorating methods and adding some +bookkeeping properties. This isn't possible (or desirable) for built-in +classes like ``list``, so trivial sub-classes are substituted to hold +decoration:: + + class InstrumentedList(list): + pass + +Collection classes can be specified in ``relationship(collection_class=)`` as +types or a function that returns an instance. Collection classes are +inspected and instrumented during the mapper compilation phase. The +collection_class callable will be executed once to produce a specimen +instance, and the type of that specimen will be instrumented. Functions that +return built-in types like ``lists`` will be adapted to produce instrumented +instances. + +When extending a known type like ``list``, additional decorations are not +generally not needed. Odds are, the extension method will delegate to a +method that's already instrumented. For example:: + + class QueueIsh(list): + def push(self, item): + self.append(item) + + def shift(self): + return self.pop(0) + +There's no need to decorate these methods. ``append`` and ``pop`` are already +instrumented as part of the ``list`` interface. Decorating them would fire +duplicate events, which should be avoided. + +The targeted decoration tries not to rely on other methods in the underlying +collection class, but some are unavoidable. Many depend on 'read' methods +being present to properly instrument a 'write', for example, ``__setitem__`` +needs ``__getitem__``. "Bulk" methods like ``update`` and ``extend`` may also +reimplemented in terms of atomic appends and removes, so the ``extend`` +decoration will actually perform many ``append`` operations and not call the +underlying method at all. + +Tight control over bulk operation and the firing of events is also possible by +implementing the instrumentation internally in your methods. The basic +instrumentation package works under the general assumption that collection +mutation will not raise unusual exceptions. If you want to closely +orchestrate append and remove events with exception management, internal +instrumentation may be the answer. Within your method, +``collection_adapter(self)`` will retrieve an object that you can use for +explicit control over triggering append and remove events. + +The owning object and :class:`.CollectionAttributeImpl` are also reachable +through the adapter, allowing for some very sophisticated behavior. + +""" +from __future__ import annotations + +import operator +import threading +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import Collection +from typing import Dict +from typing import Iterable +from typing import List +from typing import NoReturn +from typing import Optional +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from .base import NO_KEY +from .. import exc as sa_exc +from .. import util +from ..sql.base import NO_ARG +from ..util.compat import inspect_getfullargspec +from ..util.typing import Protocol + +if typing.TYPE_CHECKING: + from .attributes import AttributeEventToken + from .attributes import CollectionAttributeImpl + from .mapped_collection import attribute_keyed_dict + from .mapped_collection import column_keyed_dict + from .mapped_collection import keyfunc_mapping + from .mapped_collection import KeyFuncDict # noqa: F401 + from .state import InstanceState + + +__all__ = [ + "collection", + "collection_adapter", + "keyfunc_mapping", + "column_keyed_dict", + "attribute_keyed_dict", + "KeyFuncDict", + # old names in < 2.0 + "mapped_collection", + "column_mapped_collection", + "attribute_mapped_collection", + "MappedCollection", +] + +__instrumentation_mutex = threading.Lock() + + +_CollectionFactoryType = Callable[[], "_AdaptedCollectionProtocol"] + +_T = TypeVar("_T", bound=Any) +_KT = TypeVar("_KT", bound=Any) +_VT = TypeVar("_VT", bound=Any) +_COL = TypeVar("_COL", bound="Collection[Any]") +_FN = TypeVar("_FN", bound="Callable[..., Any]") + + +class _CollectionConverterProtocol(Protocol): + def __call__(self, collection: _COL) -> _COL: ... + + +class _AdaptedCollectionProtocol(Protocol): + _sa_adapter: CollectionAdapter + _sa_appender: Callable[..., Any] + _sa_remover: Callable[..., Any] + _sa_iterator: Callable[..., Iterable[Any]] + _sa_converter: _CollectionConverterProtocol + + +class collection: + """Decorators for entity collection classes. + + The decorators fall into two groups: annotations and interception recipes. + + The annotating decorators (appender, remover, iterator, converter, + internally_instrumented) indicate the method's purpose and take no + arguments. They are not written with parens:: + + @collection.appender + def append(self, append): ... + + The recipe decorators all require parens, even those that take no + arguments:: + + @collection.adds("entity") + def insert(self, position, entity): ... + + + @collection.removes_return() + def popitem(self): ... + + """ + + # Bundled as a class solely for ease of use: packaging, doc strings, + # importability. + + @staticmethod + def appender(fn): + """Tag the method as the collection appender. + + The appender method is called with one positional argument: the value + to append. The method will be automatically decorated with 'adds(1)' + if not already decorated:: + + @collection.appender + def add(self, append): ... + + + # or, equivalently + @collection.appender + @collection.adds(1) + def add(self, append): ... + + + # for mapping type, an 'append' may kick out a previous value + # that occupies that slot. consider d['a'] = 'foo'- any previous + # value in d['a'] is discarded. + @collection.appender + @collection.replaces(1) + def add(self, entity): + key = some_key_func(entity) + previous = None + if key in self: + previous = self[key] + self[key] = entity + return previous + + If the value to append is not allowed in the collection, you may + raise an exception. Something to remember is that the appender + will be called for each object mapped by a database query. If the + database contains rows that violate your collection semantics, you + will need to get creative to fix the problem, as access via the + collection will not work. + + If the appender method is internally instrumented, you must also + receive the keyword argument '_sa_initiator' and ensure its + promulgation to collection events. + + """ + fn._sa_instrument_role = "appender" + return fn + + @staticmethod + def remover(fn): + """Tag the method as the collection remover. + + The remover method is called with one positional argument: the value + to remove. The method will be automatically decorated with + :meth:`removes_return` if not already decorated:: + + @collection.remover + def zap(self, entity): ... + + + # or, equivalently + @collection.remover + @collection.removes_return() + def zap(self): ... + + If the value to remove is not present in the collection, you may + raise an exception or return None to ignore the error. + + If the remove method is internally instrumented, you must also + receive the keyword argument '_sa_initiator' and ensure its + promulgation to collection events. + + """ + fn._sa_instrument_role = "remover" + return fn + + @staticmethod + def iterator(fn): + """Tag the method as the collection remover. + + The iterator method is called with no arguments. It is expected to + return an iterator over all collection members:: + + @collection.iterator + def __iter__(self): ... + + """ + fn._sa_instrument_role = "iterator" + return fn + + @staticmethod + def internally_instrumented(fn): + """Tag the method as instrumented. + + This tag will prevent any decoration from being applied to the + method. Use this if you are orchestrating your own calls to + :func:`.collection_adapter` in one of the basic SQLAlchemy + interface methods, or to prevent an automatic ABC method + decoration from wrapping your implementation:: + + # normally an 'extend' method on a list-like class would be + # automatically intercepted and re-implemented in terms of + # SQLAlchemy events and append(). your implementation will + # never be called, unless: + @collection.internally_instrumented + def extend(self, items): ... + + """ + fn._sa_instrumented = True + return fn + + @staticmethod + @util.deprecated( + "1.3", + "The :meth:`.collection.converter` handler is deprecated and will " + "be removed in a future release. Please refer to the " + ":class:`.AttributeEvents.bulk_replace` listener interface in " + "conjunction with the :func:`.event.listen` function.", + ) + def converter(fn): + """Tag the method as the collection converter. + + This optional method will be called when a collection is being + replaced entirely, as in:: + + myobj.acollection = [newvalue1, newvalue2] + + The converter method will receive the object being assigned and should + return an iterable of values suitable for use by the ``appender`` + method. A converter must not assign values or mutate the collection, + its sole job is to adapt the value the user provides into an iterable + of values for the ORM's use. + + The default converter implementation will use duck-typing to do the + conversion. A dict-like collection will be convert into an iterable + of dictionary values, and other types will simply be iterated:: + + @collection.converter + def convert(self, other): ... + + If the duck-typing of the object does not match the type of this + collection, a TypeError is raised. + + Supply an implementation of this method if you want to expand the + range of possible types that can be assigned in bulk or perform + validation on the values about to be assigned. + + """ + fn._sa_instrument_role = "converter" + return fn + + @staticmethod + def adds(arg: int) -> Callable[[_FN], _FN]: + """Mark the method as adding an entity to the collection. + + Adds "add to collection" handling to the method. The decorator + argument indicates which method argument holds the SQLAlchemy-relevant + value. Arguments can be specified positionally (i.e. integer) or by + name:: + + @collection.adds(1) + def push(self, item): ... + + + @collection.adds("entity") + def do_stuff(self, thing, entity=None): ... + + """ + + def decorator(fn): + fn._sa_instrument_before = ("fire_append_event", arg) + return fn + + return decorator + + @staticmethod + def replaces(arg): + """Mark the method as replacing an entity in the collection. + + Adds "add to collection" and "remove from collection" handling to + the method. The decorator argument indicates which method argument + holds the SQLAlchemy-relevant value to be added, and return value, if + any will be considered the value to remove. + + Arguments can be specified positionally (i.e. integer) or by name:: + + @collection.replaces(2) + def __setitem__(self, index, item): ... + + """ + + def decorator(fn): + fn._sa_instrument_before = ("fire_append_event", arg) + fn._sa_instrument_after = "fire_remove_event" + return fn + + return decorator + + @staticmethod + def removes(arg): + """Mark the method as removing an entity in the collection. + + Adds "remove from collection" handling to the method. The decorator + argument indicates which method argument holds the SQLAlchemy-relevant + value to be removed. Arguments can be specified positionally (i.e. + integer) or by name:: + + @collection.removes(1) + def zap(self, item): ... + + For methods where the value to remove is not known at call-time, use + collection.removes_return. + + """ + + def decorator(fn): + fn._sa_instrument_before = ("fire_remove_event", arg) + return fn + + return decorator + + @staticmethod + def removes_return(): + """Mark the method as removing an entity in the collection. + + Adds "remove from collection" handling to the method. The return + value of the method, if any, is considered the value to remove. The + method arguments are not inspected:: + + @collection.removes_return() + def pop(self): ... + + For methods where the value to remove is known at call-time, use + collection.remove. + + """ + + def decorator(fn): + fn._sa_instrument_after = "fire_remove_event" + return fn + + return decorator + + +if TYPE_CHECKING: + + def collection_adapter(collection: Collection[Any]) -> CollectionAdapter: + """Fetch the :class:`.CollectionAdapter` for a collection.""" + +else: + collection_adapter = operator.attrgetter("_sa_adapter") + + +class CollectionAdapter: + """Bridges between the ORM and arbitrary Python collections. + + Proxies base-level collection operations (append, remove, iterate) + to the underlying Python collection, and emits add/remove events for + entities entering or leaving the collection. + + The ORM uses :class:`.CollectionAdapter` exclusively for interaction with + entity collections. + + + """ + + __slots__ = ( + "attr", + "_key", + "_data", + "owner_state", + "_converter", + "invalidated", + "empty", + ) + + attr: CollectionAttributeImpl + _key: str + + # this is actually a weakref; see note in constructor + _data: Callable[..., _AdaptedCollectionProtocol] + + owner_state: InstanceState[Any] + _converter: _CollectionConverterProtocol + invalidated: bool + empty: bool + + def __init__( + self, + attr: CollectionAttributeImpl, + owner_state: InstanceState[Any], + data: _AdaptedCollectionProtocol, + ): + self.attr = attr + self._key = attr.key + + # this weakref stays referenced throughout the lifespan of + # CollectionAdapter. so while the weakref can return None, this + # is realistically only during garbage collection of this object, so + # we type this as a callable that returns _AdaptedCollectionProtocol + # in all cases. + self._data = weakref.ref(data) # type: ignore + + self.owner_state = owner_state + data._sa_adapter = self + self._converter = data._sa_converter + self.invalidated = False + self.empty = False + + def _warn_invalidated(self) -> None: + util.warn("This collection has been invalidated.") + + @property + def data(self) -> _AdaptedCollectionProtocol: + "The entity collection being adapted." + return self._data() + + @property + def _referenced_by_owner(self) -> bool: + """return True if the owner state still refers to this collection. + + This will return False within a bulk replace operation, + where this collection is the one being replaced. + + """ + return self.owner_state.dict[self._key] is self._data() + + def bulk_appender(self): + return self._data()._sa_appender + + def append_with_event( + self, item: Any, initiator: Optional[AttributeEventToken] = None + ) -> None: + """Add an entity to the collection, firing mutation events.""" + + self._data()._sa_appender(item, _sa_initiator=initiator) + + def _set_empty(self, user_data): + assert ( + not self.empty + ), "This collection adapter is already in the 'empty' state" + self.empty = True + self.owner_state._empty_collections[self._key] = user_data + + def _reset_empty(self) -> None: + assert ( + self.empty + ), "This collection adapter is not in the 'empty' state" + self.empty = False + self.owner_state.dict[self._key] = ( + self.owner_state._empty_collections.pop(self._key) + ) + + def _refuse_empty(self) -> NoReturn: + raise sa_exc.InvalidRequestError( + "This is a special 'empty' collection which cannot accommodate " + "internal mutation operations" + ) + + def append_without_event(self, item: Any) -> None: + """Add or restore an entity to the collection, firing no events.""" + + if self.empty: + self._refuse_empty() + self._data()._sa_appender(item, _sa_initiator=False) + + def append_multiple_without_event(self, items: Iterable[Any]) -> None: + """Add or restore an entity to the collection, firing no events.""" + if self.empty: + self._refuse_empty() + appender = self._data()._sa_appender + for item in items: + appender(item, _sa_initiator=False) + + def bulk_remover(self): + return self._data()._sa_remover + + def remove_with_event( + self, item: Any, initiator: Optional[AttributeEventToken] = None + ) -> None: + """Remove an entity from the collection, firing mutation events.""" + self._data()._sa_remover(item, _sa_initiator=initiator) + + def remove_without_event(self, item: Any) -> None: + """Remove an entity from the collection, firing no events.""" + if self.empty: + self._refuse_empty() + self._data()._sa_remover(item, _sa_initiator=False) + + def clear_with_event( + self, initiator: Optional[AttributeEventToken] = None + ) -> None: + """Empty the collection, firing a mutation event for each entity.""" + + if self.empty: + self._refuse_empty() + remover = self._data()._sa_remover + for item in list(self): + remover(item, _sa_initiator=initiator) + + def clear_without_event(self) -> None: + """Empty the collection, firing no events.""" + + if self.empty: + self._refuse_empty() + remover = self._data()._sa_remover + for item in list(self): + remover(item, _sa_initiator=False) + + def __iter__(self): + """Iterate over entities in the collection.""" + + return iter(self._data()._sa_iterator()) + + def __len__(self): + """Count entities in the collection.""" + return len(list(self._data()._sa_iterator())) + + def __bool__(self): + return True + + def _fire_append_wo_mutation_event_bulk( + self, items, initiator=None, key=NO_KEY + ): + if not items: + return + + if initiator is not False: + if self.invalidated: + self._warn_invalidated() + + if self.empty: + self._reset_empty() + + for item in items: + self.attr.fire_append_wo_mutation_event( + self.owner_state, + self.owner_state.dict, + item, + initiator, + key, + ) + + def fire_append_wo_mutation_event(self, item, initiator=None, key=NO_KEY): + """Notify that a entity is entering the collection but is already + present. + + + Initiator is a token owned by the InstrumentedAttribute that + initiated the membership mutation, and should be left as None + unless you are passing along an initiator value from a chained + operation. + + .. versionadded:: 1.4.15 + + """ + if initiator is not False: + if self.invalidated: + self._warn_invalidated() + + if self.empty: + self._reset_empty() + + return self.attr.fire_append_wo_mutation_event( + self.owner_state, self.owner_state.dict, item, initiator, key + ) + else: + return item + + def fire_append_event(self, item, initiator=None, key=NO_KEY): + """Notify that a entity has entered the collection. + + Initiator is a token owned by the InstrumentedAttribute that + initiated the membership mutation, and should be left as None + unless you are passing along an initiator value from a chained + operation. + + """ + if initiator is not False: + if self.invalidated: + self._warn_invalidated() + + if self.empty: + self._reset_empty() + + return self.attr.fire_append_event( + self.owner_state, self.owner_state.dict, item, initiator, key + ) + else: + return item + + def _fire_remove_event_bulk(self, items, initiator=None, key=NO_KEY): + if not items: + return + + if initiator is not False: + if self.invalidated: + self._warn_invalidated() + + if self.empty: + self._reset_empty() + + for item in items: + self.attr.fire_remove_event( + self.owner_state, + self.owner_state.dict, + item, + initiator, + key, + ) + + def fire_remove_event(self, item, initiator=None, key=NO_KEY): + """Notify that a entity has been removed from the collection. + + Initiator is the InstrumentedAttribute that initiated the membership + mutation, and should be left as None unless you are passing along + an initiator value from a chained operation. + + """ + if initiator is not False: + if self.invalidated: + self._warn_invalidated() + + if self.empty: + self._reset_empty() + + self.attr.fire_remove_event( + self.owner_state, self.owner_state.dict, item, initiator, key + ) + + def fire_pre_remove_event(self, initiator=None, key=NO_KEY): + """Notify that an entity is about to be removed from the collection. + + Only called if the entity cannot be removed after calling + fire_remove_event(). + + """ + if self.invalidated: + self._warn_invalidated() + self.attr.fire_pre_remove_event( + self.owner_state, + self.owner_state.dict, + initiator=initiator, + key=key, + ) + + def __getstate__(self): + return { + "key": self._key, + "owner_state": self.owner_state, + "owner_cls": self.owner_state.class_, + "data": self.data, + "invalidated": self.invalidated, + "empty": self.empty, + } + + def __setstate__(self, d): + self._key = d["key"] + self.owner_state = d["owner_state"] + + # see note in constructor regarding this type: ignore + self._data = weakref.ref(d["data"]) # type: ignore + + self._converter = d["data"]._sa_converter + d["data"]._sa_adapter = self + self.invalidated = d["invalidated"] + self.attr = getattr(d["owner_cls"], self._key).impl + self.empty = d.get("empty", False) + + +def bulk_replace(values, existing_adapter, new_adapter, initiator=None): + """Load a new collection, firing events based on prior like membership. + + Appends instances in ``values`` onto the ``new_adapter``. Events will be + fired for any instance not present in the ``existing_adapter``. Any + instances in ``existing_adapter`` not present in ``values`` will have + remove events fired upon them. + + :param values: An iterable of collection member instances + + :param existing_adapter: A :class:`.CollectionAdapter` of + instances to be replaced + + :param new_adapter: An empty :class:`.CollectionAdapter` + to load with ``values`` + + + """ + + assert isinstance(values, list) + + idset = util.IdentitySet + existing_idset = idset(existing_adapter or ()) + constants = existing_idset.intersection(values or ()) + additions = idset(values or ()).difference(constants) + removals = existing_idset.difference(constants) + + appender = new_adapter.bulk_appender() + + for member in values or (): + if member in additions: + appender(member, _sa_initiator=initiator) + elif member in constants: + appender(member, _sa_initiator=False) + + if existing_adapter: + existing_adapter._fire_append_wo_mutation_event_bulk( + constants, initiator=initiator + ) + existing_adapter._fire_remove_event_bulk(removals, initiator=initiator) + + +def prepare_instrumentation( + factory: Union[Type[Collection[Any]], _CollectionFactoryType], +) -> _CollectionFactoryType: + """Prepare a callable for future use as a collection class factory. + + Given a collection class factory (either a type or no-arg callable), + return another factory that will produce compatible instances when + called. + + This function is responsible for converting collection_class=list + into the run-time behavior of collection_class=InstrumentedList. + + """ + + impl_factory: _CollectionFactoryType + + # Convert a builtin to 'Instrumented*' + if factory in __canned_instrumentation: + impl_factory = __canned_instrumentation[factory] + else: + impl_factory = cast(_CollectionFactoryType, factory) + + cls: Union[_CollectionFactoryType, Type[Collection[Any]]] + + # Create a specimen + cls = type(impl_factory()) + + # Did factory callable return a builtin? + if cls in __canned_instrumentation: + # if so, just convert. + # in previous major releases, this codepath wasn't working and was + # not covered by tests. prior to that it supplied a "wrapper" + # function that would return the class, though the rationale for this + # case is not known + impl_factory = __canned_instrumentation[cls] + cls = type(impl_factory()) + + # Instrument the class if needed. + if __instrumentation_mutex.acquire(): + try: + if getattr(cls, "_sa_instrumented", None) != id(cls): + _instrument_class(cls) + finally: + __instrumentation_mutex.release() + + return impl_factory + + +def _instrument_class(cls): + """Modify methods in a class and install instrumentation.""" + + # In the normal call flow, a request for any of the 3 basic collection + # types is transformed into one of our trivial subclasses + # (e.g. InstrumentedList). Catch anything else that sneaks in here... + if cls.__module__ == "__builtin__": + raise sa_exc.ArgumentError( + "Can not instrument a built-in type. Use a " + "subclass, even a trivial one." + ) + + roles, methods = _locate_roles_and_methods(cls) + + _setup_canned_roles(cls, roles, methods) + + _assert_required_roles(cls, roles, methods) + + _set_collection_attributes(cls, roles, methods) + + +def _locate_roles_and_methods(cls): + """search for _sa_instrument_role-decorated methods in + method resolution order, assign to roles. + + """ + + roles: Dict[str, str] = {} + methods: Dict[str, Tuple[Optional[str], Optional[int], Optional[str]]] = {} + + for supercls in cls.__mro__: + for name, method in vars(supercls).items(): + if not callable(method): + continue + + # note role declarations + if hasattr(method, "_sa_instrument_role"): + role = method._sa_instrument_role + assert role in ( + "appender", + "remover", + "iterator", + "converter", + ) + roles.setdefault(role, name) + + # transfer instrumentation requests from decorated function + # to the combined queue + before: Optional[Tuple[str, int]] = None + after: Optional[str] = None + + if hasattr(method, "_sa_instrument_before"): + op, argument = method._sa_instrument_before + assert op in ("fire_append_event", "fire_remove_event") + before = op, argument + if hasattr(method, "_sa_instrument_after"): + op = method._sa_instrument_after + assert op in ("fire_append_event", "fire_remove_event") + after = op + if before: + methods[name] = before + (after,) + elif after: + methods[name] = None, None, after + return roles, methods + + +def _setup_canned_roles(cls, roles, methods): + """see if this class has "canned" roles based on a known + collection type (dict, set, list). Apply those roles + as needed to the "roles" dictionary, and also + prepare "decorator" methods + + """ + collection_type = util.duck_type_collection(cls) + if collection_type in __interfaces: + assert collection_type is not None + canned_roles, decorators = __interfaces[collection_type] + for role, name in canned_roles.items(): + roles.setdefault(role, name) + + # apply ABC auto-decoration to methods that need it + for method, decorator in decorators.items(): + fn = getattr(cls, method, None) + if ( + fn + and method not in methods + and not hasattr(fn, "_sa_instrumented") + ): + setattr(cls, method, decorator(fn)) + + +def _assert_required_roles(cls, roles, methods): + """ensure all roles are present, and apply implicit instrumentation if + needed + + """ + if "appender" not in roles or not hasattr(cls, roles["appender"]): + raise sa_exc.ArgumentError( + "Type %s must elect an appender method to be " + "a collection class" % cls.__name__ + ) + elif roles["appender"] not in methods and not hasattr( + getattr(cls, roles["appender"]), "_sa_instrumented" + ): + methods[roles["appender"]] = ("fire_append_event", 1, None) + + if "remover" not in roles or not hasattr(cls, roles["remover"]): + raise sa_exc.ArgumentError( + "Type %s must elect a remover method to be " + "a collection class" % cls.__name__ + ) + elif roles["remover"] not in methods and not hasattr( + getattr(cls, roles["remover"]), "_sa_instrumented" + ): + methods[roles["remover"]] = ("fire_remove_event", 1, None) + + if "iterator" not in roles or not hasattr(cls, roles["iterator"]): + raise sa_exc.ArgumentError( + "Type %s must elect an iterator method to be " + "a collection class" % cls.__name__ + ) + + +def _set_collection_attributes(cls, roles, methods): + """apply ad-hoc instrumentation from decorators, class-level defaults + and implicit role declarations + + """ + for method_name, (before, argument, after) in methods.items(): + setattr( + cls, + method_name, + _instrument_membership_mutator( + getattr(cls, method_name), before, argument, after + ), + ) + # intern the role map + for role, method_name in roles.items(): + setattr(cls, "_sa_%s" % role, getattr(cls, method_name)) + + cls._sa_adapter = None + + if not hasattr(cls, "_sa_converter"): + cls._sa_converter = None + cls._sa_instrumented = id(cls) + + +def _instrument_membership_mutator(method, before, argument, after): + """Route method args and/or return value through the collection + adapter.""" + # This isn't smart enough to handle @adds(1) for 'def fn(self, (a, b))' + if before: + fn_args = list( + util.flatten_iterator(inspect_getfullargspec(method)[0]) + ) + if isinstance(argument, int): + pos_arg = argument + named_arg = len(fn_args) > argument and fn_args[argument] or None + else: + if argument in fn_args: + pos_arg = fn_args.index(argument) + else: + pos_arg = None + named_arg = argument + del fn_args + + def wrapper(*args, **kw): + if before: + if pos_arg is None: + if named_arg not in kw: + raise sa_exc.ArgumentError( + "Missing argument %s" % argument + ) + value = kw[named_arg] + else: + if len(args) > pos_arg: + value = args[pos_arg] + elif named_arg in kw: + value = kw[named_arg] + else: + raise sa_exc.ArgumentError( + "Missing argument %s" % argument + ) + + initiator = kw.pop("_sa_initiator", None) + if initiator is False: + executor = None + else: + executor = args[0]._sa_adapter + + if before and executor: + getattr(executor, before)(value, initiator) + + if not after or not executor: + return method(*args, **kw) + else: + res = method(*args, **kw) + if res is not None: + getattr(executor, after)(res, initiator) + return res + + wrapper._sa_instrumented = True # type: ignore[attr-defined] + if hasattr(method, "_sa_instrument_role"): + wrapper._sa_instrument_role = method._sa_instrument_role # type: ignore[attr-defined] # noqa: E501 + wrapper.__name__ = method.__name__ + wrapper.__doc__ = method.__doc__ + return wrapper + + +def __set_wo_mutation(collection, item, _sa_initiator=None): + """Run set wo mutation events. + + The collection is not mutated. + + """ + if _sa_initiator is not False: + executor = collection._sa_adapter + if executor: + executor.fire_append_wo_mutation_event( + item, _sa_initiator, key=None + ) + + +def __set(collection, item, _sa_initiator, key): + """Run set events. + + This event always occurs before the collection is actually mutated. + + """ + + if _sa_initiator is not False: + executor = collection._sa_adapter + if executor: + item = executor.fire_append_event(item, _sa_initiator, key=key) + return item + + +def __del(collection, item, _sa_initiator, key): + """Run del events. + + This event occurs before the collection is actually mutated, *except* + in the case of a pop operation, in which case it occurs afterwards. + For pop operations, the __before_pop hook is called before the + operation occurs. + + """ + if _sa_initiator is not False: + executor = collection._sa_adapter + if executor: + executor.fire_remove_event(item, _sa_initiator, key=key) + + +def __before_pop(collection, _sa_initiator=None): + """An event which occurs on a before a pop() operation occurs.""" + executor = collection._sa_adapter + if executor: + executor.fire_pre_remove_event(_sa_initiator) + + +def _list_decorators() -> Dict[str, Callable[[_FN], _FN]]: + """Tailored instrumentation wrappers for any list-like class.""" + + def _tidy(fn): + fn._sa_instrumented = True + fn.__doc__ = getattr(list, fn.__name__).__doc__ + + def append(fn): + def append(self, item, _sa_initiator=None): + item = __set(self, item, _sa_initiator, NO_KEY) + fn(self, item) + + _tidy(append) + return append + + def remove(fn): + def remove(self, value, _sa_initiator=None): + __del(self, value, _sa_initiator, NO_KEY) + # testlib.pragma exempt:__eq__ + fn(self, value) + + _tidy(remove) + return remove + + def insert(fn): + def insert(self, index, value): + value = __set(self, value, None, index) + fn(self, index, value) + + _tidy(insert) + return insert + + def __setitem__(fn): + def __setitem__(self, index, value): + if not isinstance(index, slice): + existing = self[index] + if existing is not None: + __del(self, existing, None, index) + value = __set(self, value, None, index) + fn(self, index, value) + else: + # slice assignment requires __delitem__, insert, __len__ + step = index.step or 1 + start = index.start or 0 + if start < 0: + start += len(self) + if index.stop is not None: + stop = index.stop + else: + stop = len(self) + if stop < 0: + stop += len(self) + + if step == 1: + if value is self: + return + for i in range(start, stop, step): + if len(self) > start: + del self[start] + + for i, item in enumerate(value): + self.insert(i + start, item) + else: + rng = list(range(start, stop, step)) + if len(value) != len(rng): + raise ValueError( + "attempt to assign sequence of size %s to " + "extended slice of size %s" + % (len(value), len(rng)) + ) + for i, item in zip(rng, value): + self.__setitem__(i, item) + + _tidy(__setitem__) + return __setitem__ + + def __delitem__(fn): + def __delitem__(self, index): + if not isinstance(index, slice): + item = self[index] + __del(self, item, None, index) + fn(self, index) + else: + # slice deletion requires __getslice__ and a slice-groking + # __getitem__ for stepped deletion + # note: not breaking this into atomic dels + for item in self[index]: + __del(self, item, None, index) + fn(self, index) + + _tidy(__delitem__) + return __delitem__ + + def extend(fn): + def extend(self, iterable): + for value in list(iterable): + self.append(value) + + _tidy(extend) + return extend + + def __iadd__(fn): + def __iadd__(self, iterable): + # list.__iadd__ takes any iterable and seems to let TypeError + # raise as-is instead of returning NotImplemented + for value in list(iterable): + self.append(value) + return self + + _tidy(__iadd__) + return __iadd__ + + def pop(fn): + def pop(self, index=-1): + __before_pop(self) + item = fn(self, index) + __del(self, item, None, index) + return item + + _tidy(pop) + return pop + + def clear(fn): + def clear(self, index=-1): + for item in self: + __del(self, item, None, index) + fn(self) + + _tidy(clear) + return clear + + # __imul__ : not wrapping this. all members of the collection are already + # present, so no need to fire appends... wrapping it with an explicit + # decorator is still possible, so events on *= can be had if they're + # desired. hard to imagine a use case for __imul__, though. + + l = locals().copy() + l.pop("_tidy") + return l + + +def _dict_decorators() -> Dict[str, Callable[[_FN], _FN]]: + """Tailored instrumentation wrappers for any dict-like mapping class.""" + + def _tidy(fn): + fn._sa_instrumented = True + fn.__doc__ = getattr(dict, fn.__name__).__doc__ + + def __setitem__(fn): + def __setitem__(self, key, value, _sa_initiator=None): + if key in self: + __del(self, self[key], _sa_initiator, key) + value = __set(self, value, _sa_initiator, key) + fn(self, key, value) + + _tidy(__setitem__) + return __setitem__ + + def __delitem__(fn): + def __delitem__(self, key, _sa_initiator=None): + if key in self: + __del(self, self[key], _sa_initiator, key) + fn(self, key) + + _tidy(__delitem__) + return __delitem__ + + def clear(fn): + def clear(self): + for key in self: + __del(self, self[key], None, key) + fn(self) + + _tidy(clear) + return clear + + def pop(fn): + def pop(self, key, default=NO_ARG): + __before_pop(self) + _to_del = key in self + if default is NO_ARG: + item = fn(self, key) + else: + item = fn(self, key, default) + if _to_del: + __del(self, item, None, key) + return item + + _tidy(pop) + return pop + + def popitem(fn): + def popitem(self): + __before_pop(self) + item = fn(self) + __del(self, item[1], None, 1) + return item + + _tidy(popitem) + return popitem + + def setdefault(fn): + def setdefault(self, key, default=None): + if key not in self: + self.__setitem__(key, default) + return default + else: + value = self.__getitem__(key) + if value is default: + __set_wo_mutation(self, value, None) + + return value + + _tidy(setdefault) + return setdefault + + def update(fn): + def update(self, __other=NO_ARG, **kw): + if __other is not NO_ARG: + if hasattr(__other, "keys"): + for key in list(__other): + if key not in self or self[key] is not __other[key]: + self[key] = __other[key] + else: + __set_wo_mutation(self, __other[key], None) + else: + for key, value in __other: + if key not in self or self[key] is not value: + self[key] = value + else: + __set_wo_mutation(self, value, None) + for key in kw: + if key not in self or self[key] is not kw[key]: + self[key] = kw[key] + else: + __set_wo_mutation(self, kw[key], None) + + _tidy(update) + return update + + l = locals().copy() + l.pop("_tidy") + return l + + +_set_binop_bases = (set, frozenset) + + +def _set_binops_check_strict(self: Any, obj: Any) -> bool: + """Allow only set, frozenset and self.__class__-derived + objects in binops.""" + return isinstance(obj, _set_binop_bases + (self.__class__,)) + + +def _set_binops_check_loose(self: Any, obj: Any) -> bool: + """Allow anything set-like to participate in set binops.""" + return ( + isinstance(obj, _set_binop_bases + (self.__class__,)) + or util.duck_type_collection(obj) == set + ) + + +def _set_decorators() -> Dict[str, Callable[[_FN], _FN]]: + """Tailored instrumentation wrappers for any set-like class.""" + + def _tidy(fn): + fn._sa_instrumented = True + fn.__doc__ = getattr(set, fn.__name__).__doc__ + + def add(fn): + def add(self, value, _sa_initiator=None): + if value not in self: + value = __set(self, value, _sa_initiator, NO_KEY) + else: + __set_wo_mutation(self, value, _sa_initiator) + # testlib.pragma exempt:__hash__ + fn(self, value) + + _tidy(add) + return add + + def discard(fn): + def discard(self, value, _sa_initiator=None): + # testlib.pragma exempt:__hash__ + if value in self: + __del(self, value, _sa_initiator, NO_KEY) + # testlib.pragma exempt:__hash__ + fn(self, value) + + _tidy(discard) + return discard + + def remove(fn): + def remove(self, value, _sa_initiator=None): + # testlib.pragma exempt:__hash__ + if value in self: + __del(self, value, _sa_initiator, NO_KEY) + # testlib.pragma exempt:__hash__ + fn(self, value) + + _tidy(remove) + return remove + + def pop(fn): + def pop(self): + __before_pop(self) + item = fn(self) + # for set in particular, we have no way to access the item + # that will be popped before pop is called. + __del(self, item, None, NO_KEY) + return item + + _tidy(pop) + return pop + + def clear(fn): + def clear(self): + for item in list(self): + self.remove(item) + + _tidy(clear) + return clear + + def update(fn): + def update(self, value): + for item in value: + self.add(item) + + _tidy(update) + return update + + def __ior__(fn): + def __ior__(self, value): + if not _set_binops_check_strict(self, value): + return NotImplemented + for item in value: + self.add(item) + return self + + _tidy(__ior__) + return __ior__ + + def difference_update(fn): + def difference_update(self, value): + for item in value: + self.discard(item) + + _tidy(difference_update) + return difference_update + + def __isub__(fn): + def __isub__(self, value): + if not _set_binops_check_strict(self, value): + return NotImplemented + for item in value: + self.discard(item) + return self + + _tidy(__isub__) + return __isub__ + + def intersection_update(fn): + def intersection_update(self, other): + want, have = self.intersection(other), set(self) + remove, add = have - want, want - have + + for item in remove: + self.remove(item) + for item in add: + self.add(item) + + _tidy(intersection_update) + return intersection_update + + def __iand__(fn): + def __iand__(self, other): + if not _set_binops_check_strict(self, other): + return NotImplemented + want, have = self.intersection(other), set(self) + remove, add = have - want, want - have + + for item in remove: + self.remove(item) + for item in add: + self.add(item) + return self + + _tidy(__iand__) + return __iand__ + + def symmetric_difference_update(fn): + def symmetric_difference_update(self, other): + want, have = self.symmetric_difference(other), set(self) + remove, add = have - want, want - have + + for item in remove: + self.remove(item) + for item in add: + self.add(item) + + _tidy(symmetric_difference_update) + return symmetric_difference_update + + def __ixor__(fn): + def __ixor__(self, other): + if not _set_binops_check_strict(self, other): + return NotImplemented + want, have = self.symmetric_difference(other), set(self) + remove, add = have - want, want - have + + for item in remove: + self.remove(item) + for item in add: + self.add(item) + return self + + _tidy(__ixor__) + return __ixor__ + + l = locals().copy() + l.pop("_tidy") + return l + + +class InstrumentedList(List[_T]): + """An instrumented version of the built-in list.""" + + +class InstrumentedSet(Set[_T]): + """An instrumented version of the built-in set.""" + + +class InstrumentedDict(Dict[_KT, _VT]): + """An instrumented version of the built-in dict.""" + + +__canned_instrumentation: util.immutabledict[Any, _CollectionFactoryType] = ( + util.immutabledict( + { + list: InstrumentedList, + set: InstrumentedSet, + dict: InstrumentedDict, + } + ) +) + +__interfaces: util.immutabledict[ + Any, + Tuple[ + Dict[str, str], + Dict[str, Callable[..., Any]], + ], +] = util.immutabledict( + { + list: ( + { + "appender": "append", + "remover": "remove", + "iterator": "__iter__", + }, + _list_decorators(), + ), + set: ( + {"appender": "add", "remover": "remove", "iterator": "__iter__"}, + _set_decorators(), + ), + # decorators are required for dicts and object collections. + dict: ({"iterator": "values"}, _dict_decorators()), + } +) + + +def __go(lcls): + global keyfunc_mapping, mapped_collection + global column_keyed_dict, column_mapped_collection + global MappedCollection, KeyFuncDict + global attribute_keyed_dict, attribute_mapped_collection + + from .mapped_collection import keyfunc_mapping + from .mapped_collection import column_keyed_dict + from .mapped_collection import attribute_keyed_dict + from .mapped_collection import KeyFuncDict + + from .mapped_collection import mapped_collection + from .mapped_collection import column_mapped_collection + from .mapped_collection import attribute_mapped_collection + from .mapped_collection import MappedCollection + + # ensure instrumentation is associated with + # these built-in classes; if a user-defined class + # subclasses these and uses @internally_instrumented, + # the superclass is otherwise not instrumented. + # see [ticket:2406]. + _instrument_class(InstrumentedList) + _instrument_class(InstrumentedSet) + _instrument_class(KeyFuncDict) + + +__go(locals()) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/context.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/context.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7c3e3c0521dc97735c15009b6186c5e280ced2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/context.py @@ -0,0 +1,3334 @@ +# orm/context.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + +from __future__ import annotations + +import itertools +from typing import Any +from typing import cast +from typing import Dict +from typing import Iterable +from typing import List +from typing import Optional +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import attributes +from . import interfaces +from . import loading +from .base import _is_aliased_class +from .interfaces import ORMColumnDescription +from .interfaces import ORMColumnsClauseRole +from .path_registry import PathRegistry +from .util import _entity_corresponds_to +from .util import _ORMJoin +from .util import _TraceAdaptRole +from .util import AliasedClass +from .util import Bundle +from .util import ORMAdapter +from .util import ORMStatementAdapter +from .. import exc as sa_exc +from .. import future +from .. import inspect +from .. import sql +from .. import util +from ..sql import coercions +from ..sql import expression +from ..sql import roles +from ..sql import util as sql_util +from ..sql import visitors +from ..sql._typing import _TP +from ..sql._typing import is_dml +from ..sql._typing import is_insert_update +from ..sql._typing import is_select_base +from ..sql.base import _select_iterables +from ..sql.base import CacheableOptions +from ..sql.base import CompileState +from ..sql.base import Executable +from ..sql.base import Generative +from ..sql.base import Options +from ..sql.dml import UpdateBase +from ..sql.elements import GroupedElement +from ..sql.elements import TextClause +from ..sql.selectable import CompoundSelectState +from ..sql.selectable import LABEL_STYLE_DISAMBIGUATE_ONLY +from ..sql.selectable import LABEL_STYLE_NONE +from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL +from ..sql.selectable import Select +from ..sql.selectable import SelectLabelStyle +from ..sql.selectable import SelectState +from ..sql.selectable import TypedReturnsRows +from ..sql.visitors import InternalTraversal + +if TYPE_CHECKING: + from ._typing import _InternalEntityType + from ._typing import OrmExecuteOptionsParameter + from .loading import PostLoad + from .mapper import Mapper + from .query import Query + from .session import _BindArguments + from .session import Session + from ..engine import Result + from ..engine.interfaces import _CoreSingleExecuteParams + from ..sql._typing import _ColumnsClauseArgument + from ..sql.compiler import SQLCompiler + from ..sql.dml import _DMLTableElement + from ..sql.elements import ColumnElement + from ..sql.selectable import _JoinTargetElement + from ..sql.selectable import _LabelConventionCallable + from ..sql.selectable import _SetupJoinsElement + from ..sql.selectable import ExecutableReturnsRows + from ..sql.selectable import SelectBase + from ..sql.type_api import TypeEngine + +_T = TypeVar("_T", bound=Any) +_path_registry = PathRegistry.root + +_EMPTY_DICT = util.immutabledict() + + +LABEL_STYLE_LEGACY_ORM = SelectLabelStyle.LABEL_STYLE_LEGACY_ORM + + +class QueryContext: + __slots__ = ( + "top_level_context", + "compile_state", + "query", + "user_passed_query", + "params", + "load_options", + "bind_arguments", + "execution_options", + "session", + "autoflush", + "populate_existing", + "invoke_all_eagers", + "version_check", + "refresh_state", + "create_eager_joins", + "propagated_loader_options", + "attributes", + "runid", + "partials", + "post_load_paths", + "identity_token", + "yield_per", + "loaders_require_buffering", + "loaders_require_uniquing", + ) + + runid: int + post_load_paths: Dict[PathRegistry, PostLoad] + compile_state: ORMCompileState + + class default_load_options(Options): + _only_return_tuples = False + _populate_existing = False + _version_check = False + _invoke_all_eagers = True + _autoflush = True + _identity_token = None + _yield_per = None + _refresh_state = None + _lazy_loaded_from = None + _legacy_uniquing = False + _sa_top_level_orm_context = None + _is_user_refresh = False + + def __init__( + self, + compile_state: CompileState, + statement: Union[Select[Any], FromStatement[Any], UpdateBase], + user_passed_query: Union[ + Select[Any], + FromStatement[Any], + UpdateBase, + ], + params: _CoreSingleExecuteParams, + session: Session, + load_options: Union[ + Type[QueryContext.default_load_options], + QueryContext.default_load_options, + ], + execution_options: Optional[OrmExecuteOptionsParameter] = None, + bind_arguments: Optional[_BindArguments] = None, + ): + self.load_options = load_options + self.execution_options = execution_options or _EMPTY_DICT + self.bind_arguments = bind_arguments or _EMPTY_DICT + self.compile_state = compile_state + self.query = statement + + # the query that the end user passed to Session.execute() or similar. + # this is usually the same as .query, except in the bulk_persistence + # routines where a separate FromStatement is manufactured in the + # compile stage; this allows differentiation in that case. + self.user_passed_query = user_passed_query + + self.session = session + self.loaders_require_buffering = False + self.loaders_require_uniquing = False + self.params = params + self.top_level_context = load_options._sa_top_level_orm_context + + cached_options = compile_state.select_statement._with_options + uncached_options = user_passed_query._with_options + + # see issue #7447 , #8399 for some background + # propagated loader options will be present on loaded InstanceState + # objects under state.load_options and are typically used by + # LazyLoader to apply options to the SELECT statement it emits. + # For compile state options (i.e. loader strategy options), these + # need to line up with the ".load_path" attribute which in + # loader.py is pulled from context.compile_state.current_path. + # so, this means these options have to be the ones from the + # *cached* statement that's travelling with compile_state, not the + # *current* statement which won't match up for an ad-hoc + # AliasedClass + self.propagated_loader_options = tuple( + opt._adapt_cached_option_to_uncached_option(self, uncached_opt) + for opt, uncached_opt in zip(cached_options, uncached_options) + if opt.propagate_to_loaders + ) + + self.attributes = dict(compile_state.attributes) + + self.autoflush = load_options._autoflush + self.populate_existing = load_options._populate_existing + self.invoke_all_eagers = load_options._invoke_all_eagers + self.version_check = load_options._version_check + self.refresh_state = load_options._refresh_state + self.yield_per = load_options._yield_per + self.identity_token = load_options._identity_token + + def _get_top_level_context(self) -> QueryContext: + return self.top_level_context or self + + +_orm_load_exec_options = util.immutabledict( + {"_result_disable_adapt_to_context": True} +) + + +class AbstractORMCompileState(CompileState): + is_dml_returning = False + + def _init_global_attributes( + self, statement, compiler, *, toplevel, process_criteria_for_toplevel + ): + self.attributes = {} + + if compiler is None: + # this is the legacy / testing only ORM _compile_state() use case. + # there is no need to apply criteria options for this. + self.global_attributes = {} + assert toplevel + return + else: + self.global_attributes = ga = compiler._global_attributes + + if toplevel: + ga["toplevel_orm"] = True + + if process_criteria_for_toplevel: + for opt in statement._with_options: + if opt._is_criteria_option: + opt.process_compile_state(self) + + return + elif ga.get("toplevel_orm", False): + return + + stack_0 = compiler.stack[0] + + try: + toplevel_stmt = stack_0["selectable"] + except KeyError: + pass + else: + for opt in toplevel_stmt._with_options: + if opt._is_compile_state and opt._is_criteria_option: + opt.process_compile_state(self) + + ga["toplevel_orm"] = True + + @classmethod + def create_for_statement( + cls, + statement: Executable, + compiler: SQLCompiler, + **kw: Any, + ) -> CompileState: + """Create a context for a statement given a :class:`.Compiler`. + + This method is always invoked in the context of SQLCompiler.process(). + + For a Select object, this would be invoked from + SQLCompiler.visit_select(). For the special FromStatement object used + by Query to indicate "Query.from_statement()", this is called by + FromStatement._compiler_dispatch() that would be called by + SQLCompiler.process(). + """ + return super().create_for_statement(statement, compiler, **kw) + + @classmethod + def orm_pre_session_exec( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + is_pre_event, + ): + raise NotImplementedError() + + @classmethod + def orm_execute_statement( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + conn, + ) -> Result: + result = conn.execute( + statement, params or {}, execution_options=execution_options + ) + return cls.orm_setup_cursor_result( + session, + statement, + params, + execution_options, + bind_arguments, + result, + ) + + @classmethod + def orm_setup_cursor_result( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + result, + ): + raise NotImplementedError() + + +class AutoflushOnlyORMCompileState(AbstractORMCompileState): + """ORM compile state that is a passthrough, except for autoflush.""" + + @classmethod + def orm_pre_session_exec( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + is_pre_event, + ): + # consume result-level load_options. These may have been set up + # in an ORMExecuteState hook + ( + load_options, + execution_options, + ) = QueryContext.default_load_options.from_execution_options( + "_sa_orm_load_options", + { + "autoflush", + }, + execution_options, + statement._execution_options, + ) + + if not is_pre_event and load_options._autoflush: + session._autoflush() + + return statement, execution_options + + @classmethod + def orm_setup_cursor_result( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + result, + ): + return result + + +class ORMCompileState(AbstractORMCompileState): + class default_compile_options(CacheableOptions): + _cache_key_traversal = [ + ("_use_legacy_query_style", InternalTraversal.dp_boolean), + ("_for_statement", InternalTraversal.dp_boolean), + ("_bake_ok", InternalTraversal.dp_boolean), + ("_current_path", InternalTraversal.dp_has_cache_key), + ("_enable_single_crit", InternalTraversal.dp_boolean), + ("_enable_eagerloads", InternalTraversal.dp_boolean), + ("_only_load_props", InternalTraversal.dp_plain_obj), + ("_set_base_alias", InternalTraversal.dp_boolean), + ("_for_refresh_state", InternalTraversal.dp_boolean), + ("_render_for_subquery", InternalTraversal.dp_boolean), + ("_is_star", InternalTraversal.dp_boolean), + ] + + # set to True by default from Query._statement_20(), to indicate + # the rendered query should look like a legacy ORM query. right + # now this basically indicates we should use tablename_columnname + # style labels. Generally indicates the statement originated + # from a Query object. + _use_legacy_query_style = False + + # set *only* when we are coming from the Query.statement + # accessor, or a Query-level equivalent such as + # query.subquery(). this supersedes "toplevel". + _for_statement = False + + _bake_ok = True + _current_path = _path_registry + _enable_single_crit = True + _enable_eagerloads = True + _only_load_props = None + _set_base_alias = False + _for_refresh_state = False + _render_for_subquery = False + _is_star = False + + attributes: Dict[Any, Any] + global_attributes: Dict[Any, Any] + + statement: Union[Select[Any], FromStatement[Any], UpdateBase] + select_statement: Union[Select[Any], FromStatement[Any], UpdateBase] + _entities: List[_QueryEntity] + _polymorphic_adapters: Dict[_InternalEntityType, ORMAdapter] + compile_options: Union[ + Type[default_compile_options], default_compile_options + ] + _primary_entity: Optional[_QueryEntity] + use_legacy_query_style: bool + _label_convention: _LabelConventionCallable + primary_columns: List[ColumnElement[Any]] + secondary_columns: List[ColumnElement[Any]] + dedupe_columns: Set[ColumnElement[Any]] + create_eager_joins: List[ + # TODO: this structure is set up by JoinedLoader + Tuple[Any, ...] + ] + current_path: PathRegistry = _path_registry + _has_mapper_entities = False + + def __init__(self, *arg, **kw): + raise NotImplementedError() + + @classmethod + def create_for_statement( + cls, + statement: Executable, + compiler: SQLCompiler, + **kw: Any, + ) -> ORMCompileState: + return cls._create_orm_context( + cast("Union[Select, FromStatement]", statement), + toplevel=not compiler.stack, + compiler=compiler, + **kw, + ) + + @classmethod + def _create_orm_context( + cls, + statement: Union[Select, FromStatement], + *, + toplevel: bool, + compiler: Optional[SQLCompiler], + **kw: Any, + ) -> ORMCompileState: + raise NotImplementedError() + + def _append_dedupe_col_collection(self, obj, col_collection): + dedupe = self.dedupe_columns + if obj not in dedupe: + dedupe.add(obj) + col_collection.append(obj) + + @classmethod + def _column_naming_convention( + cls, label_style: SelectLabelStyle, legacy: bool + ) -> _LabelConventionCallable: + if legacy: + + def name(col, col_name=None): + if col_name: + return col_name + else: + return getattr(col, "key") + + return name + else: + return SelectState._column_naming_convention(label_style) + + @classmethod + def get_column_descriptions(cls, statement): + return _column_descriptions(statement) + + @classmethod + def orm_pre_session_exec( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + is_pre_event, + ): + # consume result-level load_options. These may have been set up + # in an ORMExecuteState hook + ( + load_options, + execution_options, + ) = QueryContext.default_load_options.from_execution_options( + "_sa_orm_load_options", + { + "populate_existing", + "autoflush", + "yield_per", + "identity_token", + "sa_top_level_orm_context", + }, + execution_options, + statement._execution_options, + ) + + # default execution options for ORM results: + # 1. _result_disable_adapt_to_context=True + # this will disable the ResultSetMetadata._adapt_to_context() + # step which we don't need, as we have result processors cached + # against the original SELECT statement before caching. + + if "sa_top_level_orm_context" in execution_options: + ctx = execution_options["sa_top_level_orm_context"] + execution_options = ctx.query._execution_options.merge_with( + ctx.execution_options, execution_options + ) + + if not execution_options: + execution_options = _orm_load_exec_options + else: + execution_options = execution_options.union(_orm_load_exec_options) + + # would have been placed here by legacy Query only + if load_options._yield_per: + execution_options = execution_options.union( + {"yield_per": load_options._yield_per} + ) + + if ( + getattr(statement._compile_options, "_current_path", None) + and len(statement._compile_options._current_path) > 10 + and execution_options.get("compiled_cache", True) is not None + ): + execution_options: util.immutabledict[str, Any] = ( + execution_options.union( + { + "compiled_cache": None, + "_cache_disable_reason": "excess depth for " + "ORM loader options", + } + ) + ) + + bind_arguments["clause"] = statement + + # new in 1.4 - the coercions system is leveraged to allow the + # "subject" mapper of a statement be propagated to the top + # as the statement is built. "subject" mapper is the generally + # standard object used as an identifier for multi-database schemes. + + # we are here based on the fact that _propagate_attrs contains + # "compile_state_plugin": "orm". The "plugin_subject" + # needs to be present as well. + + try: + plugin_subject = statement._propagate_attrs["plugin_subject"] + except KeyError: + assert False, "statement had 'orm' plugin but no plugin_subject" + else: + if plugin_subject: + bind_arguments["mapper"] = plugin_subject.mapper + + if not is_pre_event and load_options._autoflush: + session._autoflush() + + return statement, execution_options + + @classmethod + def orm_setup_cursor_result( + cls, + session, + statement, + params, + execution_options, + bind_arguments, + result, + ): + execution_context = result.context + compile_state = execution_context.compiled.compile_state + + # cover edge case where ORM entities used in legacy select + # were passed to session.execute: + # session.execute(legacy_select([User.id, User.name])) + # see test_query->test_legacy_tuple_old_select + + load_options = execution_options.get( + "_sa_orm_load_options", QueryContext.default_load_options + ) + + if compile_state.compile_options._is_star: + return result + + querycontext = QueryContext( + compile_state, + statement, + statement, + params, + session, + load_options, + execution_options, + bind_arguments, + ) + return loading.instances(result, querycontext) + + @property + def _lead_mapper_entities(self): + """return all _MapperEntity objects in the lead entities collection. + + Does **not** include entities that have been replaced by + with_entities(), with_only_columns() + + """ + return [ + ent for ent in self._entities if isinstance(ent, _MapperEntity) + ] + + def _create_with_polymorphic_adapter(self, ext_info, selectable): + """given MapperEntity or ORMColumnEntity, setup polymorphic loading + if called for by the Mapper. + + As of #8168 in 2.0.0rc1, polymorphic adapters, which greatly increase + the complexity of the query creation process, are not used at all + except in the quasi-legacy cases of with_polymorphic referring to an + alias and/or subquery. This would apply to concrete polymorphic + loading, and joined inheritance where a subquery is + passed to with_polymorphic (which is completely unnecessary in modern + use). + + """ + if ( + not ext_info.is_aliased_class + and ext_info.mapper.persist_selectable + not in self._polymorphic_adapters + ): + for mp in ext_info.mapper.iterate_to_root(): + self._mapper_loads_polymorphically_with( + mp, + ORMAdapter( + _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER, + mp, + equivalents=mp._equivalent_columns, + selectable=selectable, + ), + ) + + def _mapper_loads_polymorphically_with(self, mapper, adapter): + for m2 in mapper._with_polymorphic_mappers or [mapper]: + self._polymorphic_adapters[m2] = adapter + + for m in m2.iterate_to_root(): + self._polymorphic_adapters[m.local_table] = adapter + + @classmethod + def _create_entities_collection(cls, query, legacy): + raise NotImplementedError( + "this method only works for ORMSelectCompileState" + ) + + +class _DMLReturningColFilter: + """a base for an adapter used for the DML RETURNING cases + + Has a subset of the interface used by + :class:`.ORMAdapter` and is used for :class:`._QueryEntity` + instances to set up their columns as used in RETURNING for a + DML statement. + + """ + + __slots__ = ("mapper", "columns", "__weakref__") + + def __init__(self, target_mapper, immediate_dml_mapper): + if ( + immediate_dml_mapper is not None + and target_mapper.local_table + is not immediate_dml_mapper.local_table + ): + # joined inh, or in theory other kinds of multi-table mappings + self.mapper = immediate_dml_mapper + else: + # single inh, normal mappings, etc. + self.mapper = target_mapper + self.columns = self.columns = util.WeakPopulateDict( + self.adapt_check_present # type: ignore + ) + + def __call__(self, col, as_filter): + for cc in sql_util._find_columns(col): + c2 = self.adapt_check_present(cc) + if c2 is not None: + return col + else: + return None + + def adapt_check_present(self, col): + raise NotImplementedError() + + +class _DMLBulkInsertReturningColFilter(_DMLReturningColFilter): + """an adapter used for the DML RETURNING case specifically + for ORM bulk insert (or any hypothetical DML that is splitting out a class + hierarchy among multiple DML statements....ORM bulk insert is the only + example right now) + + its main job is to limit the columns in a RETURNING to only a specific + mapped table in a hierarchy. + + """ + + def adapt_check_present(self, col): + mapper = self.mapper + prop = mapper._columntoproperty.get(col, None) + if prop is None: + return None + return mapper.local_table.c.corresponding_column(col) + + +class _DMLUpdateDeleteReturningColFilter(_DMLReturningColFilter): + """an adapter used for the DML RETURNING case specifically + for ORM enabled UPDATE/DELETE + + its main job is to limit the columns in a RETURNING to include + only direct persisted columns from the immediate selectable, not + expressions like column_property(), or to also allow columns from other + mappers for the UPDATE..FROM use case. + + """ + + def adapt_check_present(self, col): + mapper = self.mapper + prop = mapper._columntoproperty.get(col, None) + if prop is not None: + # if the col is from the immediate mapper, only return a persisted + # column, not any kind of column_property expression + return mapper.persist_selectable.c.corresponding_column(col) + + # if the col is from some other mapper, just return it, assume the + # user knows what they are doing + return col + + +@sql.base.CompileState.plugin_for("orm", "orm_from_statement") +class ORMFromStatementCompileState(ORMCompileState): + _from_obj_alias = None + _has_mapper_entities = False + + statement_container: FromStatement + requested_statement: Union[SelectBase, TextClause, UpdateBase] + dml_table: Optional[_DMLTableElement] = None + + _has_orm_entities = False + multi_row_eager_loaders = False + eager_adding_joins = False + compound_eager_adapter = None + + extra_criteria_entities = _EMPTY_DICT + eager_joins = _EMPTY_DICT + + @classmethod + def _create_orm_context( + cls, + statement: Union[Select, FromStatement], + *, + toplevel: bool, + compiler: Optional[SQLCompiler], + **kw: Any, + ) -> ORMFromStatementCompileState: + statement_container = statement + + assert isinstance(statement_container, FromStatement) + + if compiler is not None and compiler.stack: + raise sa_exc.CompileError( + "The ORM FromStatement construct only supports being " + "invoked as the topmost statement, as it is only intended to " + "define how result rows should be returned." + ) + + self = cls.__new__(cls) + self._primary_entity = None + + self.use_legacy_query_style = ( + statement_container._compile_options._use_legacy_query_style + ) + self.statement_container = self.select_statement = statement_container + self.requested_statement = statement = statement_container.element + + if statement.is_dml: + self.dml_table = statement.table + self.is_dml_returning = True + + self._entities = [] + self._polymorphic_adapters = {} + + self.compile_options = statement_container._compile_options + + if ( + self.use_legacy_query_style + and isinstance(statement, expression.SelectBase) + and not statement._is_textual + and not statement.is_dml + and statement._label_style is LABEL_STYLE_NONE + ): + self.statement = statement.set_label_style( + LABEL_STYLE_TABLENAME_PLUS_COL + ) + else: + self.statement = statement + + self._label_convention = self._column_naming_convention( + ( + statement._label_style + if not statement._is_textual and not statement.is_dml + else LABEL_STYLE_NONE + ), + self.use_legacy_query_style, + ) + + _QueryEntity.to_compile_state( + self, + statement_container._raw_columns, + self._entities, + is_current_entities=True, + ) + + self.current_path = statement_container._compile_options._current_path + + self._init_global_attributes( + statement_container, + compiler, + process_criteria_for_toplevel=False, + toplevel=True, + ) + + if statement_container._with_options: + for opt in statement_container._with_options: + if opt._is_compile_state: + opt.process_compile_state(self) + + if statement_container._with_context_options: + for fn, key in statement_container._with_context_options: + fn(self) + + self.primary_columns = [] + self.secondary_columns = [] + self.dedupe_columns = set() + self.create_eager_joins = [] + self._fallback_from_clauses = [] + + self.order_by = None + + if isinstance(self.statement, expression.TextClause): + # TextClause has no "column" objects at all. for this case, + # we generate columns from our _QueryEntity objects, then + # flip on all the "please match no matter what" parameters. + self.extra_criteria_entities = {} + + for entity in self._entities: + entity.setup_compile_state(self) + + compiler._ordered_columns = compiler._textual_ordered_columns = ( + False + ) + + # enable looser result column matching. this is shown to be + # needed by test_query.py::TextTest + compiler._loose_column_name_matching = True + + for c in self.primary_columns: + compiler.process( + c, + within_columns_clause=True, + add_to_result_map=compiler._add_to_result_map, + ) + else: + # for everyone else, Select, Insert, Update, TextualSelect, they + # have column objects already. After much + # experimentation here, the best approach seems to be, use + # those columns completely, don't interfere with the compiler + # at all; just in ORM land, use an adapter to convert from + # our ORM columns to whatever columns are in the statement, + # before we look in the result row. Adapt on names + # to accept cases such as issue #9217, however also allow + # this to be overridden for cases such as #9273. + self._from_obj_alias = ORMStatementAdapter( + _TraceAdaptRole.ADAPT_FROM_STATEMENT, + self.statement, + adapt_on_names=statement_container._adapt_on_names, + ) + + return self + + def _adapt_col_list(self, cols, current_adapter): + return cols + + def _get_current_adapter(self): + return None + + def setup_dml_returning_compile_state(self, dml_mapper): + """used by BulkORMInsert, Update, Delete to set up a handler + for RETURNING to return ORM objects and expressions + + """ + target_mapper = self.statement._propagate_attrs.get( + "plugin_subject", None + ) + + if self.statement.is_insert: + adapter = _DMLBulkInsertReturningColFilter( + target_mapper, dml_mapper + ) + elif self.statement.is_update or self.statement.is_delete: + adapter = _DMLUpdateDeleteReturningColFilter( + target_mapper, dml_mapper + ) + else: + adapter = None + + if self.compile_options._is_star and (len(self._entities) != 1): + raise sa_exc.CompileError( + "Can't generate ORM query that includes multiple expressions " + "at the same time as '*'; query for '*' alone if present" + ) + + for entity in self._entities: + entity.setup_dml_returning_compile_state(self, adapter) + + +class FromStatement(GroupedElement, Generative, TypedReturnsRows[_TP]): + """Core construct that represents a load of ORM objects from various + :class:`.ReturnsRows` and other classes including: + + :class:`.Select`, :class:`.TextClause`, :class:`.TextualSelect`, + :class:`.CompoundSelect`, :class`.Insert`, :class:`.Update`, + and in theory, :class:`.Delete`. + + """ + + __visit_name__ = "orm_from_statement" + + _compile_options = ORMFromStatementCompileState.default_compile_options + + _compile_state_factory = ORMFromStatementCompileState.create_for_statement + + _for_update_arg = None + + element: Union[ExecutableReturnsRows, TextClause] + + _adapt_on_names: bool + + _traverse_internals = [ + ("_raw_columns", InternalTraversal.dp_clauseelement_list), + ("element", InternalTraversal.dp_clauseelement), + ] + Executable._executable_traverse_internals + + _cache_key_traversal = _traverse_internals + [ + ("_compile_options", InternalTraversal.dp_has_cache_key) + ] + + is_from_statement = True + + def __init__( + self, + entities: Iterable[_ColumnsClauseArgument[Any]], + element: Union[ExecutableReturnsRows, TextClause], + _adapt_on_names: bool = True, + ): + self._raw_columns = [ + coercions.expect( + roles.ColumnsClauseRole, + ent, + apply_propagate_attrs=self, + post_inspect=True, + ) + for ent in util.to_list(entities) + ] + self.element = element + self.is_dml = element.is_dml + self.is_select = element.is_select + self.is_delete = element.is_delete + self.is_insert = element.is_insert + self.is_update = element.is_update + self._label_style = ( + element._label_style if is_select_base(element) else None + ) + self._adapt_on_names = _adapt_on_names + + def _compiler_dispatch(self, compiler, **kw): + """provide a fixed _compiler_dispatch method. + + This is roughly similar to using the sqlalchemy.ext.compiler + ``@compiles`` extension. + + """ + + compile_state = self._compile_state_factory(self, compiler, **kw) + + toplevel = not compiler.stack + + if toplevel: + compiler.compile_state = compile_state + + return compiler.process(compile_state.statement, **kw) + + @property + def column_descriptions(self): + """Return a :term:`plugin-enabled` 'column descriptions' structure + referring to the columns which are SELECTed by this statement. + + See the section :ref:`queryguide_inspection` for an overview + of this feature. + + .. seealso:: + + :ref:`queryguide_inspection` - ORM background + + """ + meth = cast( + ORMSelectCompileState, SelectState.get_plugin_class(self) + ).get_column_descriptions + return meth(self) + + def _ensure_disambiguated_names(self): + return self + + def get_children(self, **kw): + yield from itertools.chain.from_iterable( + element._from_objects for element in self._raw_columns + ) + yield from super().get_children(**kw) + + @property + def _all_selected_columns(self): + return self.element._all_selected_columns + + @property + def _return_defaults(self): + return self.element._return_defaults if is_dml(self.element) else None + + @property + def _returning(self): + return self.element._returning if is_dml(self.element) else None + + @property + def _inline(self): + return self.element._inline if is_insert_update(self.element) else None + + +@sql.base.CompileState.plugin_for("orm", "compound_select") +class CompoundSelectCompileState( + AutoflushOnlyORMCompileState, CompoundSelectState +): + pass + + +@sql.base.CompileState.plugin_for("orm", "select") +class ORMSelectCompileState(ORMCompileState, SelectState): + _already_joined_edges = () + + _memoized_entities = _EMPTY_DICT + + _from_obj_alias = None + _has_mapper_entities = False + + _has_orm_entities = False + multi_row_eager_loaders = False + eager_adding_joins = False + compound_eager_adapter = None + + correlate = None + correlate_except = None + _where_criteria = () + _having_criteria = () + + @classmethod + def _create_orm_context( + cls, + statement: Union[Select, FromStatement], + *, + toplevel: bool, + compiler: Optional[SQLCompiler], + **kw: Any, + ) -> ORMSelectCompileState: + + self = cls.__new__(cls) + + select_statement = statement + + # if we are a select() that was never a legacy Query, we won't + # have ORM level compile options. + statement._compile_options = cls.default_compile_options.safe_merge( + statement._compile_options + ) + + if select_statement._execution_options: + # execution options should not impact the compilation of a + # query, and at the moment subqueryloader is putting some things + # in here that we explicitly don't want stuck in a cache. + self.select_statement = select_statement._clone() + self.select_statement._execution_options = util.immutabledict() + else: + self.select_statement = select_statement + + # indicates this select() came from Query.statement + self.for_statement = select_statement._compile_options._for_statement + + # generally if we are from Query or directly from a select() + self.use_legacy_query_style = ( + select_statement._compile_options._use_legacy_query_style + ) + + self._entities = [] + self._primary_entity = None + self._polymorphic_adapters = {} + + self.compile_options = select_statement._compile_options + + if not toplevel: + # for subqueries, turn off eagerloads and set + # "render_for_subquery". + self.compile_options += { + "_enable_eagerloads": False, + "_render_for_subquery": True, + } + + # determine label style. we can make different decisions here. + # at the moment, trying to see if we can always use DISAMBIGUATE_ONLY + # rather than LABEL_STYLE_NONE, and if we can use disambiguate style + # for new style ORM selects too. + if ( + self.use_legacy_query_style + and self.select_statement._label_style is LABEL_STYLE_LEGACY_ORM + ): + if not self.for_statement: + self.label_style = LABEL_STYLE_TABLENAME_PLUS_COL + else: + self.label_style = LABEL_STYLE_DISAMBIGUATE_ONLY + else: + self.label_style = self.select_statement._label_style + + if select_statement._memoized_select_entities: + self._memoized_entities = { + memoized_entities: _QueryEntity.to_compile_state( + self, + memoized_entities._raw_columns, + [], + is_current_entities=False, + ) + for memoized_entities in ( + select_statement._memoized_select_entities + ) + } + + # label_convention is stateful and will yield deduping keys if it + # sees the same key twice. therefore it's important that it is not + # invoked for the above "memoized" entities that aren't actually + # in the columns clause + self._label_convention = self._column_naming_convention( + statement._label_style, self.use_legacy_query_style + ) + + _QueryEntity.to_compile_state( + self, + select_statement._raw_columns, + self._entities, + is_current_entities=True, + ) + + self.current_path = select_statement._compile_options._current_path + + self.eager_order_by = () + + self._init_global_attributes( + select_statement, + compiler, + toplevel=toplevel, + process_criteria_for_toplevel=False, + ) + + if toplevel and ( + select_statement._with_options + or select_statement._memoized_select_entities + ): + for ( + memoized_entities + ) in select_statement._memoized_select_entities: + for opt in memoized_entities._with_options: + if opt._is_compile_state: + opt.process_compile_state_replaced_entities( + self, + [ + ent + for ent in self._memoized_entities[ + memoized_entities + ] + if isinstance(ent, _MapperEntity) + ], + ) + + for opt in self.select_statement._with_options: + if opt._is_compile_state: + opt.process_compile_state(self) + + # uncomment to print out the context.attributes structure + # after it's been set up above + # self._dump_option_struct() + + if select_statement._with_context_options: + for fn, key in select_statement._with_context_options: + fn(self) + + self.primary_columns = [] + self.secondary_columns = [] + self.dedupe_columns = set() + self.eager_joins = {} + self.extra_criteria_entities = {} + self.create_eager_joins = [] + self._fallback_from_clauses = [] + + # normalize the FROM clauses early by themselves, as this makes + # it an easier job when we need to assemble a JOIN onto these, + # for select.join() as well as joinedload(). As of 1.4 there are now + # potentially more complex sets of FROM objects here as the use + # of lambda statements for lazyload, load_on_pk etc. uses more + # cloning of the select() construct. See #6495 + self.from_clauses = self._normalize_froms( + info.selectable for info in select_statement._from_obj + ) + + # this is a fairly arbitrary break into a second method, + # so it might be nicer to break up create_for_statement() + # and _setup_for_generate into three or four logical sections + self._setup_for_generate() + + SelectState.__init__(self, self.statement, compiler, **kw) + return self + + def _dump_option_struct(self): + print("\n---------------------------------------------------\n") + print(f"current path: {self.current_path}") + for key in self.attributes: + if isinstance(key, tuple) and key[0] == "loader": + print(f"\nLoader: {PathRegistry.coerce(key[1])}") + print(f" {self.attributes[key]}") + print(f" {self.attributes[key].__dict__}") + elif isinstance(key, tuple) and key[0] == "path_with_polymorphic": + print(f"\nWith Polymorphic: {PathRegistry.coerce(key[1])}") + print(f" {self.attributes[key]}") + + def _setup_for_generate(self): + query = self.select_statement + + self.statement = None + self._join_entities = () + + if self.compile_options._set_base_alias: + # legacy Query only + self._set_select_from_alias() + + for memoized_entities in query._memoized_select_entities: + if memoized_entities._setup_joins: + self._join( + memoized_entities._setup_joins, + self._memoized_entities[memoized_entities], + ) + + if query._setup_joins: + self._join(query._setup_joins, self._entities) + + current_adapter = self._get_current_adapter() + + if query._where_criteria: + self._where_criteria = query._where_criteria + + if current_adapter: + self._where_criteria = tuple( + current_adapter(crit, True) + for crit in self._where_criteria + ) + + # TODO: some complexity with order_by here was due to mapper.order_by. + # now that this is removed we can hopefully make order_by / + # group_by act identically to how they are in Core select. + self.order_by = ( + self._adapt_col_list(query._order_by_clauses, current_adapter) + if current_adapter and query._order_by_clauses not in (None, False) + else query._order_by_clauses + ) + + if query._having_criteria: + self._having_criteria = tuple( + current_adapter(crit, True) if current_adapter else crit + for crit in query._having_criteria + ) + + self.group_by = ( + self._adapt_col_list( + util.flatten_iterator(query._group_by_clauses), current_adapter + ) + if current_adapter and query._group_by_clauses not in (None, False) + else query._group_by_clauses or None + ) + + if self.eager_order_by: + adapter = self.from_clauses[0]._target_adapter + self.eager_order_by = adapter.copy_and_process(self.eager_order_by) + + if query._distinct_on: + self.distinct_on = self._adapt_col_list( + query._distinct_on, current_adapter + ) + else: + self.distinct_on = () + + self.distinct = query._distinct + + if query._correlate: + # ORM mapped entities that are mapped to joins can be passed + # to .correlate, so here they are broken into their component + # tables. + self.correlate = tuple( + util.flatten_iterator( + sql_util.surface_selectables(s) if s is not None else None + for s in query._correlate + ) + ) + elif query._correlate_except is not None: + self.correlate_except = tuple( + util.flatten_iterator( + sql_util.surface_selectables(s) if s is not None else None + for s in query._correlate_except + ) + ) + elif not query._auto_correlate: + self.correlate = (None,) + + # PART II + + self._for_update_arg = query._for_update_arg + + if self.compile_options._is_star and (len(self._entities) != 1): + raise sa_exc.CompileError( + "Can't generate ORM query that includes multiple expressions " + "at the same time as '*'; query for '*' alone if present" + ) + for entity in self._entities: + entity.setup_compile_state(self) + + for rec in self.create_eager_joins: + strategy = rec[0] + strategy(self, *rec[1:]) + + # else "load from discrete FROMs" mode, + # i.e. when each _MappedEntity has its own FROM + + if self.compile_options._enable_single_crit: + self._adjust_for_extra_criteria() + + if not self.primary_columns: + if self.compile_options._only_load_props: + assert False, "no columns were included in _only_load_props" + + raise sa_exc.InvalidRequestError( + "Query contains no columns with which to SELECT from." + ) + + if not self.from_clauses: + self.from_clauses = list(self._fallback_from_clauses) + + if self.order_by is False: + self.order_by = None + + if ( + self.multi_row_eager_loaders + and self.eager_adding_joins + and self._should_nest_selectable + ): + self.statement = self._compound_eager_statement() + else: + self.statement = self._simple_statement() + + if self.for_statement: + ezero = self._mapper_zero() + if ezero is not None: + # TODO: this goes away once we get rid of the deep entity + # thing + self.statement = self.statement._annotate( + {"deepentity": ezero} + ) + + @classmethod + def _create_entities_collection(cls, query, legacy): + """Creates a partial ORMSelectCompileState that includes + the full collection of _MapperEntity and other _QueryEntity objects. + + Supports a few remaining use cases that are pre-compilation + but still need to gather some of the column / adaption information. + + """ + self = cls.__new__(cls) + + self._entities = [] + self._primary_entity = None + self._polymorphic_adapters = {} + + self._label_convention = self._column_naming_convention( + query._label_style, legacy + ) + + # entities will also set up polymorphic adapters for mappers + # that have with_polymorphic configured + _QueryEntity.to_compile_state( + self, query._raw_columns, self._entities, is_current_entities=True + ) + return self + + @classmethod + def determine_last_joined_entity(cls, statement): + setup_joins = statement._setup_joins + + return _determine_last_joined_entity(setup_joins, None) + + @classmethod + def all_selected_columns(cls, statement): + for element in statement._raw_columns: + if ( + element.is_selectable + and "entity_namespace" in element._annotations + ): + ens = element._annotations["entity_namespace"] + if not ens.is_mapper and not ens.is_aliased_class: + yield from _select_iterables([element]) + else: + yield from _select_iterables(ens._all_column_expressions) + else: + yield from _select_iterables([element]) + + @classmethod + def get_columns_clause_froms(cls, statement): + return cls._normalize_froms( + itertools.chain.from_iterable( + ( + element._from_objects + if "parententity" not in element._annotations + else [ + element._annotations[ + "parententity" + ].__clause_element__() + ] + ) + for element in statement._raw_columns + ) + ) + + @classmethod + def from_statement(cls, statement, from_statement): + from_statement = coercions.expect( + roles.ReturnsRowsRole, + from_statement, + apply_propagate_attrs=statement, + ) + + stmt = FromStatement(statement._raw_columns, from_statement) + + stmt.__dict__.update( + _with_options=statement._with_options, + _with_context_options=statement._with_context_options, + _execution_options=statement._execution_options, + _propagate_attrs=statement._propagate_attrs, + ) + return stmt + + def _set_select_from_alias(self): + """used only for legacy Query cases""" + + query = self.select_statement # query + + assert self.compile_options._set_base_alias + assert len(query._from_obj) == 1 + + adapter = self._get_select_from_alias_from_obj(query._from_obj[0]) + if adapter: + self.compile_options += {"_enable_single_crit": False} + self._from_obj_alias = adapter + + def _get_select_from_alias_from_obj(self, from_obj): + """used only for legacy Query cases""" + + info = from_obj + + if "parententity" in info._annotations: + info = info._annotations["parententity"] + + if hasattr(info, "mapper"): + if not info.is_aliased_class: + raise sa_exc.ArgumentError( + "A selectable (FromClause) instance is " + "expected when the base alias is being set." + ) + else: + return info._adapter + + elif isinstance(info.selectable, sql.selectable.AliasedReturnsRows): + equivs = self._all_equivs() + assert info is info.selectable + return ORMStatementAdapter( + _TraceAdaptRole.LEGACY_SELECT_FROM_ALIAS, + info.selectable, + equivalents=equivs, + ) + else: + return None + + def _mapper_zero(self): + """return the Mapper associated with the first QueryEntity.""" + return self._entities[0].mapper + + def _entity_zero(self): + """Return the 'entity' (mapper or AliasedClass) associated + with the first QueryEntity, or alternatively the 'select from' + entity if specified.""" + + for ent in self.from_clauses: + if "parententity" in ent._annotations: + return ent._annotations["parententity"] + for qent in self._entities: + if qent.entity_zero: + return qent.entity_zero + + return None + + def _only_full_mapper_zero(self, methname): + if self._entities != [self._primary_entity]: + raise sa_exc.InvalidRequestError( + "%s() can only be used against " + "a single mapped class." % methname + ) + return self._primary_entity.entity_zero + + def _only_entity_zero(self, rationale=None): + if len(self._entities) > 1: + raise sa_exc.InvalidRequestError( + rationale + or "This operation requires a Query " + "against a single mapper." + ) + return self._entity_zero() + + def _all_equivs(self): + equivs = {} + + for memoized_entities in self._memoized_entities.values(): + for ent in [ + ent + for ent in memoized_entities + if isinstance(ent, _MapperEntity) + ]: + equivs.update(ent.mapper._equivalent_columns) + + for ent in [ + ent for ent in self._entities if isinstance(ent, _MapperEntity) + ]: + equivs.update(ent.mapper._equivalent_columns) + return equivs + + def _compound_eager_statement(self): + # for eager joins present and LIMIT/OFFSET/DISTINCT, + # wrap the query inside a select, + # then append eager joins onto that + + if self.order_by: + # the default coercion for ORDER BY is now the OrderByRole, + # which adds an additional post coercion to ByOfRole in that + # elements are converted into label references. For the + # eager load / subquery wrapping case, we need to un-coerce + # the original expressions outside of the label references + # in order to have them render. + unwrapped_order_by = [ + ( + elem.element + if isinstance(elem, sql.elements._label_reference) + else elem + ) + for elem in self.order_by + ] + + order_by_col_expr = sql_util.expand_column_list_from_order_by( + self.primary_columns, unwrapped_order_by + ) + else: + order_by_col_expr = [] + unwrapped_order_by = None + + # put FOR UPDATE on the inner query, where MySQL will honor it, + # as well as if it has an OF so PostgreSQL can use it. + inner = self._select_statement( + self.primary_columns + + [c for c in order_by_col_expr if c not in self.dedupe_columns], + self.from_clauses, + self._where_criteria, + self._having_criteria, + self.label_style, + self.order_by, + for_update=self._for_update_arg, + hints=self.select_statement._hints, + statement_hints=self.select_statement._statement_hints, + correlate=self.correlate, + correlate_except=self.correlate_except, + **self._select_args, + ) + + inner = inner.alias() + + equivs = self._all_equivs() + + self.compound_eager_adapter = ORMStatementAdapter( + _TraceAdaptRole.COMPOUND_EAGER_STATEMENT, inner, equivalents=equivs + ) + + statement = future.select( + *([inner] + self.secondary_columns) # use_labels=self.labels + ) + statement._label_style = self.label_style + + # Oracle Database however does not allow FOR UPDATE on the subquery, + # and the Oracle Database dialects ignore it, plus for PostgreSQL, + # MySQL we expect that all elements of the row are locked, so also put + # it on the outside (except in the case of PG when OF is used) + if ( + self._for_update_arg is not None + and self._for_update_arg.of is None + ): + statement._for_update_arg = self._for_update_arg + + from_clause = inner + for eager_join in self.eager_joins.values(): + # EagerLoader places a 'stop_on' attribute on the join, + # giving us a marker as to where the "splice point" of + # the join should be + from_clause = sql_util.splice_joins( + from_clause, eager_join, eager_join.stop_on + ) + + statement.select_from.non_generative(statement, from_clause) + + if unwrapped_order_by: + statement.order_by.non_generative( + statement, + *self.compound_eager_adapter.copy_and_process( + unwrapped_order_by + ), + ) + + statement.order_by.non_generative(statement, *self.eager_order_by) + return statement + + def _simple_statement(self): + statement = self._select_statement( + self.primary_columns + self.secondary_columns, + tuple(self.from_clauses) + tuple(self.eager_joins.values()), + self._where_criteria, + self._having_criteria, + self.label_style, + self.order_by, + for_update=self._for_update_arg, + hints=self.select_statement._hints, + statement_hints=self.select_statement._statement_hints, + correlate=self.correlate, + correlate_except=self.correlate_except, + **self._select_args, + ) + + if self.eager_order_by: + statement.order_by.non_generative(statement, *self.eager_order_by) + return statement + + def _select_statement( + self, + raw_columns, + from_obj, + where_criteria, + having_criteria, + label_style, + order_by, + for_update, + hints, + statement_hints, + correlate, + correlate_except, + limit_clause, + offset_clause, + fetch_clause, + fetch_clause_options, + distinct, + distinct_on, + prefixes, + suffixes, + group_by, + independent_ctes, + independent_ctes_opts, + ): + statement = Select._create_raw_select( + _raw_columns=raw_columns, + _from_obj=from_obj, + _label_style=label_style, + ) + + if where_criteria: + statement._where_criteria = where_criteria + if having_criteria: + statement._having_criteria = having_criteria + + if order_by: + statement._order_by_clauses += tuple(order_by) + + if distinct_on: + statement.distinct.non_generative(statement, *distinct_on) + elif distinct: + statement.distinct.non_generative(statement) + + if group_by: + statement._group_by_clauses += tuple(group_by) + + statement._limit_clause = limit_clause + statement._offset_clause = offset_clause + statement._fetch_clause = fetch_clause + statement._fetch_clause_options = fetch_clause_options + statement._independent_ctes = independent_ctes + statement._independent_ctes_opts = independent_ctes_opts + + if prefixes: + statement._prefixes = prefixes + + if suffixes: + statement._suffixes = suffixes + + statement._for_update_arg = for_update + + if hints: + statement._hints = hints + if statement_hints: + statement._statement_hints = statement_hints + + if correlate: + statement.correlate.non_generative(statement, *correlate) + + if correlate_except is not None: + statement.correlate_except.non_generative( + statement, *correlate_except + ) + + return statement + + def _adapt_polymorphic_element(self, element): + if "parententity" in element._annotations: + search = element._annotations["parententity"] + alias = self._polymorphic_adapters.get(search, None) + if alias: + return alias.adapt_clause(element) + + if isinstance(element, expression.FromClause): + search = element + elif hasattr(element, "table"): + search = element.table + else: + return None + + alias = self._polymorphic_adapters.get(search, None) + if alias: + return alias.adapt_clause(element) + + def _adapt_col_list(self, cols, current_adapter): + if current_adapter: + return [current_adapter(o, True) for o in cols] + else: + return cols + + def _get_current_adapter(self): + adapters = [] + + if self._from_obj_alias: + # used for legacy going forward for query set_ops, e.g. + # union(), union_all(), etc. + # 1.4 and previously, also used for from_self(), + # select_entity_from() + # + # for the "from obj" alias, apply extra rule to the + # 'ORM only' check, if this query were generated from a + # subquery of itself, i.e. _from_selectable(), apply adaption + # to all SQL constructs. + adapters.append( + ( + True, + self._from_obj_alias.replace, + ) + ) + + # this was *hopefully* the only adapter we were going to need + # going forward...however, we unfortunately need _from_obj_alias + # for query.union(), which we can't drop + if self._polymorphic_adapters: + adapters.append((False, self._adapt_polymorphic_element)) + + if not adapters: + return None + + def _adapt_clause(clause, as_filter): + # do we adapt all expression elements or only those + # tagged as 'ORM' constructs ? + + def replace(elem): + is_orm_adapt = ( + "_orm_adapt" in elem._annotations + or "parententity" in elem._annotations + ) + for always_adapt, adapter in adapters: + if is_orm_adapt or always_adapt: + e = adapter(elem) + if e is not None: + return e + + return visitors.replacement_traverse(clause, {}, replace) + + return _adapt_clause + + def _join(self, args, entities_collection): + for right, onclause, from_, flags in args: + isouter = flags["isouter"] + full = flags["full"] + + right = inspect(right) + if onclause is not None: + onclause = inspect(onclause) + + if isinstance(right, interfaces.PropComparator): + if onclause is not None: + raise sa_exc.InvalidRequestError( + "No 'on clause' argument may be passed when joining " + "to a relationship path as a target" + ) + + onclause = right + right = None + elif "parententity" in right._annotations: + right = right._annotations["parententity"] + + if onclause is None: + if not right.is_selectable and not hasattr(right, "mapper"): + raise sa_exc.ArgumentError( + "Expected mapped entity or " + "selectable/table as join target" + ) + + if isinstance(onclause, interfaces.PropComparator): + # descriptor/property given (or determined); this tells us + # explicitly what the expected "left" side of the join is. + + of_type = getattr(onclause, "_of_type", None) + + if right is None: + if of_type: + right = of_type + else: + right = onclause.property + + try: + right = right.entity + except AttributeError as err: + raise sa_exc.ArgumentError( + "Join target %s does not refer to a " + "mapped entity" % right + ) from err + + left = onclause._parententity + + prop = onclause.property + if not isinstance(onclause, attributes.QueryableAttribute): + onclause = prop + + # check for this path already present. don't render in that + # case. + if (left, right, prop.key) in self._already_joined_edges: + continue + + if from_ is not None: + if ( + from_ is not left + and from_._annotations.get("parententity", None) + is not left + ): + raise sa_exc.InvalidRequestError( + "explicit from clause %s does not match left side " + "of relationship attribute %s" + % ( + from_._annotations.get("parententity", from_), + onclause, + ) + ) + elif from_ is not None: + prop = None + left = from_ + else: + # no descriptor/property given; we will need to figure out + # what the effective "left" side is + prop = left = None + + # figure out the final "left" and "right" sides and create an + # ORMJoin to add to our _from_obj tuple + self._join_left_to_right( + entities_collection, + left, + right, + onclause, + prop, + isouter, + full, + ) + + def _join_left_to_right( + self, + entities_collection, + left, + right, + onclause, + prop, + outerjoin, + full, + ): + """given raw "left", "right", "onclause" parameters consumed from + a particular key within _join(), add a real ORMJoin object to + our _from_obj list (or augment an existing one) + + """ + + if left is None: + # left not given (e.g. no relationship object/name specified) + # figure out the best "left" side based on our existing froms / + # entities + assert prop is None + ( + left, + replace_from_obj_index, + use_entity_index, + ) = self._join_determine_implicit_left_side( + entities_collection, left, right, onclause + ) + else: + # left is given via a relationship/name, or as explicit left side. + # Determine where in our + # "froms" list it should be spliced/appended as well as what + # existing entity it corresponds to. + ( + replace_from_obj_index, + use_entity_index, + ) = self._join_place_explicit_left_side(entities_collection, left) + + if left is right: + raise sa_exc.InvalidRequestError( + "Can't construct a join from %s to %s, they " + "are the same entity" % (left, right) + ) + + # the right side as given often needs to be adapted. additionally + # a lot of things can be wrong with it. handle all that and + # get back the new effective "right" side + r_info, right, onclause = self._join_check_and_adapt_right_side( + left, right, onclause, prop + ) + + if not r_info.is_selectable: + extra_criteria = self._get_extra_criteria(r_info) + else: + extra_criteria = () + + if replace_from_obj_index is not None: + # splice into an existing element in the + # self._from_obj list + left_clause = self.from_clauses[replace_from_obj_index] + + self.from_clauses = ( + self.from_clauses[:replace_from_obj_index] + + [ + _ORMJoin( + left_clause, + right, + onclause, + isouter=outerjoin, + full=full, + _extra_criteria=extra_criteria, + ) + ] + + self.from_clauses[replace_from_obj_index + 1 :] + ) + else: + # add a new element to the self._from_obj list + if use_entity_index is not None: + # make use of _MapperEntity selectable, which is usually + # entity_zero.selectable, but if with_polymorphic() were used + # might be distinct + assert isinstance( + entities_collection[use_entity_index], _MapperEntity + ) + left_clause = entities_collection[use_entity_index].selectable + else: + left_clause = left + + self.from_clauses = self.from_clauses + [ + _ORMJoin( + left_clause, + r_info, + onclause, + isouter=outerjoin, + full=full, + _extra_criteria=extra_criteria, + ) + ] + + def _join_determine_implicit_left_side( + self, entities_collection, left, right, onclause + ): + """When join conditions don't express the left side explicitly, + determine if an existing FROM or entity in this query + can serve as the left hand side. + + """ + + # when we are here, it means join() was called without an ORM- + # specific way of telling us what the "left" side is, e.g.: + # + # join(RightEntity) + # + # or + # + # join(RightEntity, RightEntity.foo == LeftEntity.bar) + # + + r_info = inspect(right) + + replace_from_obj_index = use_entity_index = None + + if self.from_clauses: + # we have a list of FROMs already. So by definition this + # join has to connect to one of those FROMs. + + indexes = sql_util.find_left_clause_to_join_from( + self.from_clauses, r_info.selectable, onclause + ) + + if len(indexes) == 1: + replace_from_obj_index = indexes[0] + left = self.from_clauses[replace_from_obj_index] + elif len(indexes) > 1: + raise sa_exc.InvalidRequestError( + "Can't determine which FROM clause to join " + "from, there are multiple FROMS which can " + "join to this entity. Please use the .select_from() " + "method to establish an explicit left side, as well as " + "providing an explicit ON clause if not present already " + "to help resolve the ambiguity." + ) + else: + raise sa_exc.InvalidRequestError( + "Don't know how to join to %r. " + "Please use the .select_from() " + "method to establish an explicit left side, as well as " + "providing an explicit ON clause if not present already " + "to help resolve the ambiguity." % (right,) + ) + + elif entities_collection: + # we have no explicit FROMs, so the implicit left has to + # come from our list of entities. + + potential = {} + for entity_index, ent in enumerate(entities_collection): + entity = ent.entity_zero_or_selectable + if entity is None: + continue + ent_info = inspect(entity) + if ent_info is r_info: # left and right are the same, skip + continue + + # by using a dictionary with the selectables as keys this + # de-duplicates those selectables as occurs when the query is + # against a series of columns from the same selectable + if isinstance(ent, _MapperEntity): + potential[ent.selectable] = (entity_index, entity) + else: + potential[ent_info.selectable] = (None, entity) + + all_clauses = list(potential.keys()) + indexes = sql_util.find_left_clause_to_join_from( + all_clauses, r_info.selectable, onclause + ) + + if len(indexes) == 1: + use_entity_index, left = potential[all_clauses[indexes[0]]] + elif len(indexes) > 1: + raise sa_exc.InvalidRequestError( + "Can't determine which FROM clause to join " + "from, there are multiple FROMS which can " + "join to this entity. Please use the .select_from() " + "method to establish an explicit left side, as well as " + "providing an explicit ON clause if not present already " + "to help resolve the ambiguity." + ) + else: + raise sa_exc.InvalidRequestError( + "Don't know how to join to %r. " + "Please use the .select_from() " + "method to establish an explicit left side, as well as " + "providing an explicit ON clause if not present already " + "to help resolve the ambiguity." % (right,) + ) + else: + raise sa_exc.InvalidRequestError( + "No entities to join from; please use " + "select_from() to establish the left " + "entity/selectable of this join" + ) + + return left, replace_from_obj_index, use_entity_index + + def _join_place_explicit_left_side(self, entities_collection, left): + """When join conditions express a left side explicitly, determine + where in our existing list of FROM clauses we should join towards, + or if we need to make a new join, and if so is it from one of our + existing entities. + + """ + + # when we are here, it means join() was called with an indicator + # as to an exact left side, which means a path to a + # Relationship was given, e.g.: + # + # join(RightEntity, LeftEntity.right) + # + # or + # + # join(LeftEntity.right) + # + # as well as string forms: + # + # join(RightEntity, "right") + # + # etc. + # + + replace_from_obj_index = use_entity_index = None + + l_info = inspect(left) + if self.from_clauses: + indexes = sql_util.find_left_clause_that_matches_given( + self.from_clauses, l_info.selectable + ) + + if len(indexes) > 1: + raise sa_exc.InvalidRequestError( + "Can't identify which entity in which to assign the " + "left side of this join. Please use a more specific " + "ON clause." + ) + + # have an index, means the left side is already present in + # an existing FROM in the self._from_obj tuple + if indexes: + replace_from_obj_index = indexes[0] + + # no index, means we need to add a new element to the + # self._from_obj tuple + + # no from element present, so we will have to add to the + # self._from_obj tuple. Determine if this left side matches up + # with existing mapper entities, in which case we want to apply the + # aliasing / adaptation rules present on that entity if any + if ( + replace_from_obj_index is None + and entities_collection + and hasattr(l_info, "mapper") + ): + for idx, ent in enumerate(entities_collection): + # TODO: should we be checking for multiple mapper entities + # matching? + if isinstance(ent, _MapperEntity) and ent.corresponds_to(left): + use_entity_index = idx + break + + return replace_from_obj_index, use_entity_index + + def _join_check_and_adapt_right_side(self, left, right, onclause, prop): + """transform the "right" side of the join as well as the onclause + according to polymorphic mapping translations, aliasing on the query + or on the join, special cases where the right and left side have + overlapping tables. + + """ + + l_info = inspect(left) + r_info = inspect(right) + + overlap = False + + right_mapper = getattr(r_info, "mapper", None) + # if the target is a joined inheritance mapping, + # be more liberal about auto-aliasing. + if right_mapper and ( + right_mapper.with_polymorphic + or isinstance(right_mapper.persist_selectable, expression.Join) + ): + for from_obj in self.from_clauses or [l_info.selectable]: + if sql_util.selectables_overlap( + l_info.selectable, from_obj + ) and sql_util.selectables_overlap( + from_obj, r_info.selectable + ): + overlap = True + break + + if overlap and l_info.selectable is r_info.selectable: + raise sa_exc.InvalidRequestError( + "Can't join table/selectable '%s' to itself" + % l_info.selectable + ) + + right_mapper, right_selectable, right_is_aliased = ( + getattr(r_info, "mapper", None), + r_info.selectable, + getattr(r_info, "is_aliased_class", False), + ) + + if ( + right_mapper + and prop + and not right_mapper.common_parent(prop.mapper) + ): + raise sa_exc.InvalidRequestError( + "Join target %s does not correspond to " + "the right side of join condition %s" % (right, onclause) + ) + + # _join_entities is used as a hint for single-table inheritance + # purposes at the moment + if hasattr(r_info, "mapper"): + self._join_entities += (r_info,) + + need_adapter = False + + # test for joining to an unmapped selectable as the target + if r_info.is_clause_element: + if prop: + right_mapper = prop.mapper + + if right_selectable._is_lateral: + # orm_only is disabled to suit the case where we have to + # adapt an explicit correlate(Entity) - the select() loses + # the ORM-ness in this case right now, ideally it would not + current_adapter = self._get_current_adapter() + if current_adapter is not None: + # TODO: we had orm_only=False here before, removing + # it didn't break things. if we identify the rationale, + # may need to apply "_orm_only" annotation here. + right = current_adapter(right, True) + + elif prop: + # joining to selectable with a mapper property given + # as the ON clause + + if not right_selectable.is_derived_from( + right_mapper.persist_selectable + ): + raise sa_exc.InvalidRequestError( + "Selectable '%s' is not derived from '%s'" + % ( + right_selectable.description, + right_mapper.persist_selectable.description, + ) + ) + + # if the destination selectable is a plain select(), + # turn it into an alias(). + if isinstance(right_selectable, expression.SelectBase): + right_selectable = coercions.expect( + roles.FromClauseRole, right_selectable + ) + need_adapter = True + + # make the right hand side target into an ORM entity + right = AliasedClass(right_mapper, right_selectable) + + util.warn_deprecated( + "An alias is being generated automatically against " + "joined entity %s for raw clauseelement, which is " + "deprecated and will be removed in a later release. " + "Use the aliased() " + "construct explicitly, see the linked example." + % right_mapper, + "1.4", + code="xaj1", + ) + + # test for overlap: + # orm/inheritance/relationships.py + # SelfReferentialM2MTest + aliased_entity = right_mapper and not right_is_aliased and overlap + + if not need_adapter and aliased_entity: + # there are a few places in the ORM that automatic aliasing + # is still desirable, and can't be automatic with a Core + # only approach. For illustrations of "overlaps" see + # test/orm/inheritance/test_relationships.py. There are also + # general overlap cases with many-to-many tables where automatic + # aliasing is desirable. + right = AliasedClass(right, flat=True) + need_adapter = True + + util.warn( + "An alias is being generated automatically against " + "joined entity %s due to overlapping tables. This is a " + "legacy pattern which may be " + "deprecated in a later release. Use the " + "aliased(, flat=True) " + "construct explicitly, see the linked example." % right_mapper, + code="xaj2", + ) + + if need_adapter: + # if need_adapter is True, we are in a deprecated case and + # a warning has been emitted. + assert right_mapper + + adapter = ORMAdapter( + _TraceAdaptRole.DEPRECATED_JOIN_ADAPT_RIGHT_SIDE, + inspect(right), + equivalents=right_mapper._equivalent_columns, + ) + + # if an alias() on the right side was generated, + # which is intended to wrap a the right side in a subquery, + # ensure that columns retrieved from this target in the result + # set are also adapted. + self._mapper_loads_polymorphically_with(right_mapper, adapter) + elif ( + not r_info.is_clause_element + and not right_is_aliased + and right_mapper._has_aliased_polymorphic_fromclause + ): + # for the case where the target mapper has a with_polymorphic + # set up, ensure an adapter is set up for criteria that works + # against this mapper. Previously, this logic used to + # use the "create_aliases or aliased_entity" case to generate + # an aliased() object, but this creates an alias that isn't + # strictly necessary. + # see test/orm/test_core_compilation.py + # ::RelNaturalAliasedJoinsTest::test_straight + # and similar + self._mapper_loads_polymorphically_with( + right_mapper, + ORMAdapter( + _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER_RIGHT_JOIN, + right_mapper, + selectable=right_mapper.selectable, + equivalents=right_mapper._equivalent_columns, + ), + ) + # if the onclause is a ClauseElement, adapt it with any + # adapters that are in place right now + if isinstance(onclause, expression.ClauseElement): + current_adapter = self._get_current_adapter() + if current_adapter: + onclause = current_adapter(onclause, True) + + # if joining on a MapperProperty path, + # track the path to prevent redundant joins + if prop: + self._already_joined_edges += ((left, right, prop.key),) + + return inspect(right), right, onclause + + @property + def _select_args(self): + return { + "limit_clause": self.select_statement._limit_clause, + "offset_clause": self.select_statement._offset_clause, + "distinct": self.distinct, + "distinct_on": self.distinct_on, + "prefixes": self.select_statement._prefixes, + "suffixes": self.select_statement._suffixes, + "group_by": self.group_by or None, + "fetch_clause": self.select_statement._fetch_clause, + "fetch_clause_options": ( + self.select_statement._fetch_clause_options + ), + "independent_ctes": self.select_statement._independent_ctes, + "independent_ctes_opts": ( + self.select_statement._independent_ctes_opts + ), + } + + @property + def _should_nest_selectable(self): + kwargs = self._select_args + return ( + kwargs.get("limit_clause") is not None + or kwargs.get("offset_clause") is not None + or kwargs.get("distinct", False) + or kwargs.get("distinct_on", ()) + or kwargs.get("group_by", False) + ) + + def _get_extra_criteria(self, ext_info): + if ( + "additional_entity_criteria", + ext_info.mapper, + ) in self.global_attributes: + return tuple( + ae._resolve_where_criteria(ext_info) + for ae in self.global_attributes[ + ("additional_entity_criteria", ext_info.mapper) + ] + if (ae.include_aliases or ae.entity is ext_info) + and ae._should_include(self) + ) + else: + return () + + def _adjust_for_extra_criteria(self): + """Apply extra criteria filtering. + + For all distinct single-table-inheritance mappers represented in + the columns clause of this query, as well as the "select from entity", + add criterion to the WHERE + clause of the given QueryContext such that only the appropriate + subtypes are selected from the total results. + + Additionally, add WHERE criteria originating from LoaderCriteriaOptions + associated with the global context. + + """ + + for fromclause in self.from_clauses: + ext_info = fromclause._annotations.get("parententity", None) + + if ( + ext_info + and ( + ext_info.mapper._single_table_criterion is not None + or ("additional_entity_criteria", ext_info.mapper) + in self.global_attributes + ) + and ext_info not in self.extra_criteria_entities + ): + self.extra_criteria_entities[ext_info] = ( + ext_info, + ext_info._adapter if ext_info.is_aliased_class else None, + ) + + search = set(self.extra_criteria_entities.values()) + + for ext_info, adapter in search: + if ext_info in self._join_entities: + continue + + single_crit = ext_info.mapper._single_table_criterion + + if self.compile_options._for_refresh_state: + additional_entity_criteria = [] + else: + additional_entity_criteria = self._get_extra_criteria(ext_info) + + if single_crit is not None: + additional_entity_criteria += (single_crit,) + + current_adapter = self._get_current_adapter() + for crit in additional_entity_criteria: + if adapter: + crit = adapter.traverse(crit) + + if current_adapter: + crit = sql_util._deep_annotate(crit, {"_orm_adapt": True}) + crit = current_adapter(crit, False) + self._where_criteria += (crit,) + + +def _column_descriptions( + query_or_select_stmt: Union[Query, Select, FromStatement], + compile_state: Optional[ORMSelectCompileState] = None, + legacy: bool = False, +) -> List[ORMColumnDescription]: + if compile_state is None: + compile_state = ORMSelectCompileState._create_entities_collection( + query_or_select_stmt, legacy=legacy + ) + ctx = compile_state + d = [ + { + "name": ent._label_name, + "type": ent.type, + "aliased": getattr(insp_ent, "is_aliased_class", False), + "expr": ent.expr, + "entity": ( + getattr(insp_ent, "entity", None) + if ent.entity_zero is not None + and not insp_ent.is_clause_element + else None + ), + } + for ent, insp_ent in [ + (_ent, _ent.entity_zero) for _ent in ctx._entities + ] + ] + return d + + +def _legacy_filter_by_entity_zero( + query_or_augmented_select: Union[Query[Any], Select[Any]], +) -> Optional[_InternalEntityType[Any]]: + self = query_or_augmented_select + if self._setup_joins: + _last_joined_entity = self._last_joined_entity + if _last_joined_entity is not None: + return _last_joined_entity + + if self._from_obj and "parententity" in self._from_obj[0]._annotations: + return self._from_obj[0]._annotations["parententity"] + + return _entity_from_pre_ent_zero(self) + + +def _entity_from_pre_ent_zero( + query_or_augmented_select: Union[Query[Any], Select[Any]], +) -> Optional[_InternalEntityType[Any]]: + self = query_or_augmented_select + if not self._raw_columns: + return None + + ent = self._raw_columns[0] + + if "parententity" in ent._annotations: + return ent._annotations["parententity"] + elif isinstance(ent, ORMColumnsClauseRole): + return ent.entity + elif "bundle" in ent._annotations: + return ent._annotations["bundle"] + else: + return ent + + +def _determine_last_joined_entity( + setup_joins: Tuple[_SetupJoinsElement, ...], + entity_zero: Optional[_InternalEntityType[Any]] = None, +) -> Optional[Union[_InternalEntityType[Any], _JoinTargetElement]]: + if not setup_joins: + return None + + (target, onclause, from_, flags) = setup_joins[-1] + + if isinstance( + target, + attributes.QueryableAttribute, + ): + return target.entity + else: + return target + + +class _QueryEntity: + """represent an entity column returned within a Query result.""" + + __slots__ = () + + supports_single_entity: bool + + _non_hashable_value = False + _null_column_type = False + use_id_for_hash = False + + _label_name: Optional[str] + type: Union[Type[Any], TypeEngine[Any]] + expr: Union[_InternalEntityType, ColumnElement[Any]] + entity_zero: Optional[_InternalEntityType] + + def setup_compile_state(self, compile_state: ORMCompileState) -> None: + raise NotImplementedError() + + def setup_dml_returning_compile_state( + self, + compile_state: ORMCompileState, + adapter: Optional[_DMLReturningColFilter], + ) -> None: + raise NotImplementedError() + + def row_processor(self, context, result): + raise NotImplementedError() + + @classmethod + def to_compile_state( + cls, compile_state, entities, entities_collection, is_current_entities + ): + for idx, entity in enumerate(entities): + if entity._is_lambda_element: + if entity._is_sequence: + cls.to_compile_state( + compile_state, + entity._resolved, + entities_collection, + is_current_entities, + ) + continue + else: + entity = entity._resolved + + if entity.is_clause_element: + if entity.is_selectable: + if "parententity" in entity._annotations: + _MapperEntity( + compile_state, + entity, + entities_collection, + is_current_entities, + ) + else: + _ColumnEntity._for_columns( + compile_state, + entity._select_iterable, + entities_collection, + idx, + is_current_entities, + ) + else: + if entity._annotations.get("bundle", False): + _BundleEntity( + compile_state, + entity, + entities_collection, + is_current_entities, + ) + elif entity._is_clause_list: + # this is legacy only - test_composites.py + # test_query_cols_legacy + _ColumnEntity._for_columns( + compile_state, + entity._select_iterable, + entities_collection, + idx, + is_current_entities, + ) + else: + _ColumnEntity._for_columns( + compile_state, + [entity], + entities_collection, + idx, + is_current_entities, + ) + elif entity.is_bundle: + _BundleEntity(compile_state, entity, entities_collection) + + return entities_collection + + +class _MapperEntity(_QueryEntity): + """mapper/class/AliasedClass entity""" + + __slots__ = ( + "expr", + "mapper", + "entity_zero", + "is_aliased_class", + "path", + "_extra_entities", + "_label_name", + "_with_polymorphic_mappers", + "selectable", + "_polymorphic_discriminator", + ) + + expr: _InternalEntityType + mapper: Mapper[Any] + entity_zero: _InternalEntityType + is_aliased_class: bool + path: PathRegistry + _label_name: str + + def __init__( + self, compile_state, entity, entities_collection, is_current_entities + ): + entities_collection.append(self) + if is_current_entities: + if compile_state._primary_entity is None: + compile_state._primary_entity = self + compile_state._has_mapper_entities = True + compile_state._has_orm_entities = True + + entity = entity._annotations["parententity"] + entity._post_inspect + ext_info = self.entity_zero = entity + entity = ext_info.entity + + self.expr = entity + self.mapper = mapper = ext_info.mapper + + self._extra_entities = (self.expr,) + + if ext_info.is_aliased_class: + self._label_name = ext_info.name + else: + self._label_name = mapper.class_.__name__ + + self.is_aliased_class = ext_info.is_aliased_class + self.path = ext_info._path_registry + + self.selectable = ext_info.selectable + self._with_polymorphic_mappers = ext_info.with_polymorphic_mappers + self._polymorphic_discriminator = ext_info.polymorphic_on + + if mapper._should_select_with_poly_adapter: + compile_state._create_with_polymorphic_adapter( + ext_info, self.selectable + ) + + supports_single_entity = True + + _non_hashable_value = True + use_id_for_hash = True + + @property + def type(self): + return self.mapper.class_ + + @property + def entity_zero_or_selectable(self): + return self.entity_zero + + def corresponds_to(self, entity): + return _entity_corresponds_to(self.entity_zero, entity) + + def _get_entity_clauses(self, compile_state): + adapter = None + + if not self.is_aliased_class: + if compile_state._polymorphic_adapters: + adapter = compile_state._polymorphic_adapters.get( + self.mapper, None + ) + else: + adapter = self.entity_zero._adapter + + if adapter: + if compile_state._from_obj_alias: + ret = adapter.wrap(compile_state._from_obj_alias) + else: + ret = adapter + else: + ret = compile_state._from_obj_alias + + return ret + + def row_processor(self, context, result): + compile_state = context.compile_state + adapter = self._get_entity_clauses(compile_state) + + if compile_state.compound_eager_adapter and adapter: + adapter = adapter.wrap(compile_state.compound_eager_adapter) + elif not adapter: + adapter = compile_state.compound_eager_adapter + + if compile_state._primary_entity is self: + only_load_props = compile_state.compile_options._only_load_props + refresh_state = context.refresh_state + else: + only_load_props = refresh_state = None + + _instance = loading._instance_processor( + self, + self.mapper, + context, + result, + self.path, + adapter, + only_load_props=only_load_props, + refresh_state=refresh_state, + polymorphic_discriminator=self._polymorphic_discriminator, + ) + + return _instance, self._label_name, self._extra_entities + + def setup_dml_returning_compile_state( + self, + compile_state: ORMCompileState, + adapter: Optional[_DMLReturningColFilter], + ) -> None: + loading._setup_entity_query( + compile_state, + self.mapper, + self, + self.path, + adapter, + compile_state.primary_columns, + with_polymorphic=self._with_polymorphic_mappers, + only_load_props=compile_state.compile_options._only_load_props, + polymorphic_discriminator=self._polymorphic_discriminator, + ) + + def setup_compile_state(self, compile_state): + adapter = self._get_entity_clauses(compile_state) + + single_table_crit = self.mapper._single_table_criterion + if ( + single_table_crit is not None + or ("additional_entity_criteria", self.mapper) + in compile_state.global_attributes + ): + ext_info = self.entity_zero + compile_state.extra_criteria_entities[ext_info] = ( + ext_info, + ext_info._adapter if ext_info.is_aliased_class else None, + ) + + loading._setup_entity_query( + compile_state, + self.mapper, + self, + self.path, + adapter, + compile_state.primary_columns, + with_polymorphic=self._with_polymorphic_mappers, + only_load_props=compile_state.compile_options._only_load_props, + polymorphic_discriminator=self._polymorphic_discriminator, + ) + compile_state._fallback_from_clauses.append(self.selectable) + + +class _BundleEntity(_QueryEntity): + _extra_entities = () + + __slots__ = ( + "bundle", + "expr", + "type", + "_label_name", + "_entities", + "supports_single_entity", + ) + + _entities: List[_QueryEntity] + bundle: Bundle + type: Type[Any] + _label_name: str + supports_single_entity: bool + expr: Bundle + + def __init__( + self, + compile_state, + expr, + entities_collection, + is_current_entities, + setup_entities=True, + parent_bundle=None, + ): + compile_state._has_orm_entities = True + + expr = expr._annotations["bundle"] + if parent_bundle: + parent_bundle._entities.append(self) + else: + entities_collection.append(self) + + if isinstance( + expr, (attributes.QueryableAttribute, interfaces.PropComparator) + ): + bundle = expr.__clause_element__() + else: + bundle = expr + + self.bundle = self.expr = bundle + self.type = type(bundle) + self._label_name = bundle.name + self._entities = [] + + if setup_entities: + for expr in bundle.exprs: + if "bundle" in expr._annotations: + _BundleEntity( + compile_state, + expr, + entities_collection, + is_current_entities, + parent_bundle=self, + ) + elif isinstance(expr, Bundle): + _BundleEntity( + compile_state, + expr, + entities_collection, + is_current_entities, + parent_bundle=self, + ) + else: + _ORMColumnEntity._for_columns( + compile_state, + [expr], + entities_collection, + None, + is_current_entities, + parent_bundle=self, + ) + + self.supports_single_entity = self.bundle.single_entity + + @property + def mapper(self): + ezero = self.entity_zero + if ezero is not None: + return ezero.mapper + else: + return None + + @property + def entity_zero(self): + for ent in self._entities: + ezero = ent.entity_zero + if ezero is not None: + return ezero + else: + return None + + def corresponds_to(self, entity): + # TODO: we might be able to implement this but for now + # we are working around it + return False + + @property + def entity_zero_or_selectable(self): + for ent in self._entities: + ezero = ent.entity_zero_or_selectable + if ezero is not None: + return ezero + else: + return None + + def setup_compile_state(self, compile_state): + for ent in self._entities: + ent.setup_compile_state(compile_state) + + def setup_dml_returning_compile_state( + self, + compile_state: ORMCompileState, + adapter: Optional[_DMLReturningColFilter], + ) -> None: + return self.setup_compile_state(compile_state) + + def row_processor(self, context, result): + procs, labels, extra = zip( + *[ent.row_processor(context, result) for ent in self._entities] + ) + + proc = self.bundle.create_row_processor(context.query, procs, labels) + + return proc, self._label_name, self._extra_entities + + +class _ColumnEntity(_QueryEntity): + __slots__ = ( + "_fetch_column", + "_row_processor", + "raw_column_index", + "translate_raw_column", + ) + + @classmethod + def _for_columns( + cls, + compile_state, + columns, + entities_collection, + raw_column_index, + is_current_entities, + parent_bundle=None, + ): + for column in columns: + annotations = column._annotations + if "parententity" in annotations: + _entity = annotations["parententity"] + else: + _entity = sql_util.extract_first_column_annotation( + column, "parententity" + ) + + if _entity: + if "identity_token" in column._annotations: + _IdentityTokenEntity( + compile_state, + column, + entities_collection, + _entity, + raw_column_index, + is_current_entities, + parent_bundle=parent_bundle, + ) + else: + _ORMColumnEntity( + compile_state, + column, + entities_collection, + _entity, + raw_column_index, + is_current_entities, + parent_bundle=parent_bundle, + ) + else: + _RawColumnEntity( + compile_state, + column, + entities_collection, + raw_column_index, + is_current_entities, + parent_bundle=parent_bundle, + ) + + @property + def type(self): + return self.column.type + + @property + def _non_hashable_value(self): + return not self.column.type.hashable + + @property + def _null_column_type(self): + return self.column.type._isnull + + def row_processor(self, context, result): + compile_state = context.compile_state + + # the resulting callable is entirely cacheable so just return + # it if we already made one + if self._row_processor is not None: + getter, label_name, extra_entities = self._row_processor + if self.translate_raw_column: + extra_entities += ( + context.query._raw_columns[self.raw_column_index], + ) + + return getter, label_name, extra_entities + + # retrieve the column that would have been set up in + # setup_compile_state, to avoid doing redundant work + if self._fetch_column is not None: + column = self._fetch_column + else: + # fetch_column will be None when we are doing a from_statement + # and setup_compile_state may not have been called. + column = self.column + + # previously, the RawColumnEntity didn't look for from_obj_alias + # however I can't think of a case where we would be here and + # we'd want to ignore it if this is the from_statement use case. + # it's not really a use case to have raw columns + from_statement + if compile_state._from_obj_alias: + column = compile_state._from_obj_alias.columns[column] + + if column._annotations: + # annotated columns perform more slowly in compiler and + # result due to the __eq__() method, so use deannotated + column = column._deannotate() + + if compile_state.compound_eager_adapter: + column = compile_state.compound_eager_adapter.columns[column] + + getter = result._getter(column) + ret = getter, self._label_name, self._extra_entities + self._row_processor = ret + + if self.translate_raw_column: + extra_entities = self._extra_entities + ( + context.query._raw_columns[self.raw_column_index], + ) + return getter, self._label_name, extra_entities + else: + return ret + + +class _RawColumnEntity(_ColumnEntity): + entity_zero = None + mapper = None + supports_single_entity = False + + __slots__ = ( + "expr", + "column", + "_label_name", + "entity_zero_or_selectable", + "_extra_entities", + ) + + def __init__( + self, + compile_state, + column, + entities_collection, + raw_column_index, + is_current_entities, + parent_bundle=None, + ): + self.expr = column + self.raw_column_index = raw_column_index + self.translate_raw_column = raw_column_index is not None + + if column._is_star: + compile_state.compile_options += {"_is_star": True} + + if not is_current_entities or column._is_text_clause: + self._label_name = None + else: + if parent_bundle: + self._label_name = column._proxy_key + else: + self._label_name = compile_state._label_convention(column) + + if parent_bundle: + parent_bundle._entities.append(self) + else: + entities_collection.append(self) + + self.column = column + self.entity_zero_or_selectable = ( + self.column._from_objects[0] if self.column._from_objects else None + ) + self._extra_entities = (self.expr, self.column) + self._fetch_column = self._row_processor = None + + def corresponds_to(self, entity): + return False + + def setup_dml_returning_compile_state( + self, + compile_state: ORMCompileState, + adapter: Optional[_DMLReturningColFilter], + ) -> None: + return self.setup_compile_state(compile_state) + + def setup_compile_state(self, compile_state): + current_adapter = compile_state._get_current_adapter() + if current_adapter: + column = current_adapter(self.column, False) + if column is None: + return + else: + column = self.column + + if column._annotations: + # annotated columns perform more slowly in compiler and + # result due to the __eq__() method, so use deannotated + column = column._deannotate() + + compile_state.dedupe_columns.add(column) + compile_state.primary_columns.append(column) + self._fetch_column = column + + +class _ORMColumnEntity(_ColumnEntity): + """Column/expression based entity.""" + + supports_single_entity = False + + __slots__ = ( + "expr", + "mapper", + "column", + "_label_name", + "entity_zero_or_selectable", + "entity_zero", + "_extra_entities", + ) + + def __init__( + self, + compile_state, + column, + entities_collection, + parententity, + raw_column_index, + is_current_entities, + parent_bundle=None, + ): + annotations = column._annotations + + _entity = parententity + + # an AliasedClass won't have proxy_key in the annotations for + # a column if it was acquired using the class' adapter directly, + # such as using AliasedInsp._adapt_element(). this occurs + # within internal loaders. + + orm_key = annotations.get("proxy_key", None) + proxy_owner = annotations.get("proxy_owner", _entity) + if orm_key: + self.expr = getattr(proxy_owner.entity, orm_key) + self.translate_raw_column = False + else: + # if orm_key is not present, that means this is an ad-hoc + # SQL ColumnElement, like a CASE() or other expression. + # include this column position from the invoked statement + # in the ORM-level ResultSetMetaData on each execute, so that + # it can be targeted by identity after caching + self.expr = column + self.translate_raw_column = raw_column_index is not None + + self.raw_column_index = raw_column_index + + if is_current_entities: + if parent_bundle: + self._label_name = orm_key if orm_key else column._proxy_key + else: + self._label_name = compile_state._label_convention( + column, col_name=orm_key + ) + else: + self._label_name = None + + _entity._post_inspect + self.entity_zero = self.entity_zero_or_selectable = ezero = _entity + self.mapper = mapper = _entity.mapper + + if parent_bundle: + parent_bundle._entities.append(self) + else: + entities_collection.append(self) + + compile_state._has_orm_entities = True + + self.column = column + + self._fetch_column = self._row_processor = None + + self._extra_entities = (self.expr, self.column) + + if mapper._should_select_with_poly_adapter: + compile_state._create_with_polymorphic_adapter( + ezero, ezero.selectable + ) + + def corresponds_to(self, entity): + if _is_aliased_class(entity): + # TODO: polymorphic subclasses ? + return entity is self.entity_zero + else: + return not _is_aliased_class( + self.entity_zero + ) and entity.common_parent(self.entity_zero) + + def setup_dml_returning_compile_state( + self, + compile_state: ORMCompileState, + adapter: Optional[_DMLReturningColFilter], + ) -> None: + + self._fetch_column = column = self.column + if adapter: + column = adapter(column, False) + + if column is not None: + compile_state.dedupe_columns.add(column) + compile_state.primary_columns.append(column) + + def setup_compile_state(self, compile_state): + current_adapter = compile_state._get_current_adapter() + if current_adapter: + column = current_adapter(self.column, False) + if column is None: + assert compile_state.is_dml_returning + self._fetch_column = self.column + return + else: + column = self.column + + ezero = self.entity_zero + + single_table_crit = self.mapper._single_table_criterion + if ( + single_table_crit is not None + or ("additional_entity_criteria", self.mapper) + in compile_state.global_attributes + ): + compile_state.extra_criteria_entities[ezero] = ( + ezero, + ezero._adapter if ezero.is_aliased_class else None, + ) + + if column._annotations and not column._expression_label: + # annotated columns perform more slowly in compiler and + # result due to the __eq__() method, so use deannotated + column = column._deannotate() + + # use entity_zero as the from if we have it. this is necessary + # for polymorphic scenarios where our FROM is based on ORM entity, + # not the FROM of the column. but also, don't use it if our column + # doesn't actually have any FROMs that line up, such as when its + # a scalar subquery. + if set(self.column._from_objects).intersection( + ezero.selectable._from_objects + ): + compile_state._fallback_from_clauses.append(ezero.selectable) + + compile_state.dedupe_columns.add(column) + compile_state.primary_columns.append(column) + self._fetch_column = column + + +class _IdentityTokenEntity(_ORMColumnEntity): + translate_raw_column = False + + def setup_compile_state(self, compile_state): + pass + + def row_processor(self, context, result): + def getter(row): + return context.load_options._identity_token + + return getter, self._label_name, self._extra_entities diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_api.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_api.py new file mode 100644 index 0000000000000000000000000000000000000000..52d69cff15fc76fda75b2db6d3887078bbc15360 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_api.py @@ -0,0 +1,2004 @@ +# orm/decl_api.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Public API functions and helpers for declarative.""" + +from __future__ import annotations + +import itertools +import re +import typing +from typing import Any +from typing import Callable +from typing import ClassVar +from typing import Dict +from typing import FrozenSet +from typing import Generic +from typing import Iterable +from typing import Iterator +from typing import Mapping +from typing import Optional +from typing import overload +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import attributes +from . import clsregistry +from . import instrumentation +from . import interfaces +from . import mapperlib +from ._orm_constructors import composite +from ._orm_constructors import deferred +from ._orm_constructors import mapped_column +from ._orm_constructors import relationship +from ._orm_constructors import synonym +from .attributes import InstrumentedAttribute +from .base import _inspect_mapped_class +from .base import _is_mapped_class +from .base import Mapped +from .base import ORMDescriptor +from .decl_base import _add_attribute +from .decl_base import _as_declarative +from .decl_base import _ClassScanMapperConfig +from .decl_base import _declarative_constructor +from .decl_base import _DeferredMapperConfig +from .decl_base import _del_attribute +from .decl_base import _mapper +from .descriptor_props import Composite +from .descriptor_props import Synonym +from .descriptor_props import Synonym as _orm_synonym +from .mapper import Mapper +from .properties import MappedColumn +from .relationships import RelationshipProperty +from .state import InstanceState +from .. import exc +from .. import inspection +from .. import util +from ..sql import sqltypes +from ..sql.base import _NoArg +from ..sql.elements import SQLCoreOperations +from ..sql.schema import MetaData +from ..sql.selectable import FromClause +from ..util import hybridmethod +from ..util import hybridproperty +from ..util import typing as compat_typing +from ..util import warn_deprecated +from ..util.typing import CallableReference +from ..util.typing import de_optionalize_union_types +from ..util.typing import flatten_newtype +from ..util.typing import is_generic +from ..util.typing import is_literal +from ..util.typing import is_newtype +from ..util.typing import is_pep593 +from ..util.typing import is_pep695 +from ..util.typing import Literal +from ..util.typing import LITERAL_TYPES +from ..util.typing import Self + +if TYPE_CHECKING: + from ._typing import _O + from ._typing import _RegistryType + from .decl_base import _DataclassArguments + from .instrumentation import ClassManager + from .interfaces import MapperProperty + from .state import InstanceState # noqa + from ..sql._typing import _TypeEngineArgument + from ..sql.type_api import _MatchedOnType + +_T = TypeVar("_T", bound=Any) + +_TT = TypeVar("_TT", bound=Any) + +# it's not clear how to have Annotated, Union objects etc. as keys here +# from a typing perspective so just leave it open ended for now +_TypeAnnotationMapType = Mapping[Any, "_TypeEngineArgument[Any]"] +_MutableTypeAnnotationMapType = Dict[Any, "_TypeEngineArgument[Any]"] + +_DeclaredAttrDecorated = Callable[ + ..., Union[Mapped[_T], ORMDescriptor[_T], SQLCoreOperations[_T]] +] + + +def has_inherited_table(cls: Type[_O]) -> bool: + """Given a class, return True if any of the classes it inherits from has a + mapped table, otherwise return False. + + This is used in declarative mixins to build attributes that behave + differently for the base class vs. a subclass in an inheritance + hierarchy. + + .. seealso:: + + :ref:`decl_mixin_inheritance` + + """ + for class_ in cls.__mro__[1:]: + if getattr(class_, "__table__", None) is not None: + return True + return False + + +class _DynamicAttributesType(type): + def __setattr__(cls, key: str, value: Any) -> None: + if "__mapper__" in cls.__dict__: + _add_attribute(cls, key, value) + else: + type.__setattr__(cls, key, value) + + def __delattr__(cls, key: str) -> None: + if "__mapper__" in cls.__dict__: + _del_attribute(cls, key) + else: + type.__delattr__(cls, key) + + +class DeclarativeAttributeIntercept( + _DynamicAttributesType, + # Inspectable is used only by the mypy plugin + inspection.Inspectable[Mapper[Any]], +): + """Metaclass that may be used in conjunction with the + :class:`_orm.DeclarativeBase` class to support addition of class + attributes dynamically. + + """ + + +@compat_typing.dataclass_transform( + field_specifiers=( + MappedColumn, + RelationshipProperty, + Composite, + Synonym, + mapped_column, + relationship, + composite, + synonym, + deferred, + ), +) +class DCTransformDeclarative(DeclarativeAttributeIntercept): + """metaclass that includes @dataclass_transforms""" + + +class DeclarativeMeta(DeclarativeAttributeIntercept): + metadata: MetaData + registry: RegistryType + + def __init__( + cls, classname: Any, bases: Any, dict_: Any, **kw: Any + ) -> None: + # use cls.__dict__, which can be modified by an + # __init_subclass__() method (#7900) + dict_ = cls.__dict__ + + # early-consume registry from the initial declarative base, + # assign privately to not conflict with subclass attributes named + # "registry" + reg = getattr(cls, "_sa_registry", None) + if reg is None: + reg = dict_.get("registry", None) + if not isinstance(reg, registry): + raise exc.InvalidRequestError( + "Declarative base class has no 'registry' attribute, " + "or registry is not a sqlalchemy.orm.registry() object" + ) + else: + cls._sa_registry = reg + + if not cls.__dict__.get("__abstract__", False): + _as_declarative(reg, cls, dict_) + type.__init__(cls, classname, bases, dict_) + + +def synonym_for( + name: str, map_column: bool = False +) -> Callable[[Callable[..., Any]], Synonym[Any]]: + """Decorator that produces an :func:`_orm.synonym` + attribute in conjunction with a Python descriptor. + + The function being decorated is passed to :func:`_orm.synonym` as the + :paramref:`.orm.synonym.descriptor` parameter:: + + class MyClass(Base): + __tablename__ = "my_table" + + id = Column(Integer, primary_key=True) + _job_status = Column("job_status", String(50)) + + @synonym_for("job_status") + @property + def job_status(self): + return "Status: %s" % self._job_status + + The :ref:`hybrid properties ` feature of SQLAlchemy + is typically preferred instead of synonyms, which is a more legacy + feature. + + .. seealso:: + + :ref:`synonyms` - Overview of synonyms + + :func:`_orm.synonym` - the mapper-level function + + :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an + updated approach to augmenting attribute behavior more flexibly than + can be achieved with synonyms. + + """ + + def decorate(fn: Callable[..., Any]) -> Synonym[Any]: + return _orm_synonym(name, map_column=map_column, descriptor=fn) + + return decorate + + +class _declared_attr_common: + def __init__( + self, + fn: Callable[..., Any], + cascading: bool = False, + quiet: bool = False, + ): + # support + # @declared_attr + # @classmethod + # def foo(cls) -> Mapped[thing]: + # ... + # which seems to help typing tools interpret the fn as a classmethod + # for situations where needed + if isinstance(fn, classmethod): + fn = fn.__func__ + + self.fget = fn + self._cascading = cascading + self._quiet = quiet + self.__doc__ = fn.__doc__ + + def _collect_return_annotation(self) -> Optional[Type[Any]]: + return util.get_annotations(self.fget).get("return") + + def __get__(self, instance: Optional[object], owner: Any) -> Any: + # the declared_attr needs to make use of a cache that exists + # for the span of the declarative scan_attributes() phase. + # to achieve this we look at the class manager that's configured. + + # note this method should not be called outside of the declarative + # setup phase + + cls = owner + manager = attributes.opt_manager_of_class(cls) + if manager is None: + if not re.match(r"^__.+__$", self.fget.__name__): + # if there is no manager at all, then this class hasn't been + # run through declarative or mapper() at all, emit a warning. + util.warn( + "Unmanaged access of declarative attribute %s from " + "non-mapped class %s" % (self.fget.__name__, cls.__name__) + ) + return self.fget(cls) + elif manager.is_mapped: + # the class is mapped, which means we're outside of the declarative + # scan setup, just run the function. + return self.fget(cls) + + # here, we are inside of the declarative scan. use the registry + # that is tracking the values of these attributes. + declarative_scan = manager.declarative_scan() + + # assert that we are in fact in the declarative scan + assert declarative_scan is not None + + reg = declarative_scan.declared_attr_reg + + if self in reg: + return reg[self] + else: + reg[self] = obj = self.fget(cls) + return obj + + +class _declared_directive(_declared_attr_common, Generic[_T]): + # see mapping_api.rst for docstring + + if typing.TYPE_CHECKING: + + def __init__( + self, + fn: Callable[..., _T], + cascading: bool = False, + ): ... + + def __get__(self, instance: Optional[object], owner: Any) -> _T: ... + + def __set__(self, instance: Any, value: Any) -> None: ... + + def __delete__(self, instance: Any) -> None: ... + + def __call__(self, fn: Callable[..., _TT]) -> _declared_directive[_TT]: + # extensive fooling of mypy underway... + ... + + +class declared_attr(interfaces._MappedAttribute[_T], _declared_attr_common): + """Mark a class-level method as representing the definition of + a mapped property or Declarative directive. + + :class:`_orm.declared_attr` is typically applied as a decorator to a class + level method, turning the attribute into a scalar-like property that can be + invoked from the uninstantiated class. The Declarative mapping process + looks for these :class:`_orm.declared_attr` callables as it scans classes, + and assumes any attribute marked with :class:`_orm.declared_attr` will be a + callable that will produce an object specific to the Declarative mapping or + table configuration. + + :class:`_orm.declared_attr` is usually applicable to + :ref:`mixins `, to define relationships that are to be + applied to different implementors of the class. It may also be used to + define dynamically generated column expressions and other Declarative + attributes. + + Example:: + + class ProvidesUserMixin: + "A mixin that adds a 'user' relationship to classes." + + user_id: Mapped[int] = mapped_column(ForeignKey("user_table.id")) + + @declared_attr + def user(cls) -> Mapped["User"]: + return relationship("User") + + When used with Declarative directives such as ``__tablename__``, the + :meth:`_orm.declared_attr.directive` modifier may be used which indicates + to :pep:`484` typing tools that the given method is not dealing with + :class:`_orm.Mapped` attributes:: + + class CreateTableName: + @declared_attr.directive + def __tablename__(cls) -> str: + return cls.__name__.lower() + + :class:`_orm.declared_attr` can also be applied directly to mapped + classes, to allow for attributes that dynamically configure themselves + on subclasses when using mapped inheritance schemes. Below + illustrates :class:`_orm.declared_attr` to create a dynamic scheme + for generating the :paramref:`_orm.Mapper.polymorphic_identity` parameter + for subclasses:: + + class Employee(Base): + __tablename__ = "employee" + + id: Mapped[int] = mapped_column(primary_key=True) + type: Mapped[str] = mapped_column(String(50)) + + @declared_attr.directive + def __mapper_args__(cls) -> Dict[str, Any]: + if cls.__name__ == "Employee": + return { + "polymorphic_on": cls.type, + "polymorphic_identity": "Employee", + } + else: + return {"polymorphic_identity": cls.__name__} + + + class Engineer(Employee): + pass + + :class:`_orm.declared_attr` supports decorating functions that are + explicitly decorated with ``@classmethod``. This is never necessary from a + runtime perspective, however may be needed in order to support :pep:`484` + typing tools that don't otherwise recognize the decorated function as + having class-level behaviors for the ``cls`` parameter:: + + class SomethingMixin: + x: Mapped[int] + y: Mapped[int] + + @declared_attr + @classmethod + def x_plus_y(cls) -> Mapped[int]: + return column_property(cls.x + cls.y) + + .. versionadded:: 2.0 - :class:`_orm.declared_attr` can accommodate a + function decorated with ``@classmethod`` to help with :pep:`484` + integration where needed. + + + .. seealso:: + + :ref:`orm_mixins_toplevel` - Declarative Mixin documentation with + background on use patterns for :class:`_orm.declared_attr`. + + """ # noqa: E501 + + if typing.TYPE_CHECKING: + + def __init__( + self, + fn: _DeclaredAttrDecorated[_T], + cascading: bool = False, + ): ... + + def __set__(self, instance: Any, value: Any) -> None: ... + + def __delete__(self, instance: Any) -> None: ... + + # this is the Mapped[] API where at class descriptor get time we want + # the type checker to see InstrumentedAttribute[_T]. However the + # callable function prior to mapping in fact calls the given + # declarative function that does not return InstrumentedAttribute + @overload + def __get__( + self, instance: None, owner: Any + ) -> InstrumentedAttribute[_T]: ... + + @overload + def __get__(self, instance: object, owner: Any) -> _T: ... + + def __get__( + self, instance: Optional[object], owner: Any + ) -> Union[InstrumentedAttribute[_T], _T]: ... + + @hybridmethod + def _stateful(cls, **kw: Any) -> _stateful_declared_attr[_T]: + return _stateful_declared_attr(**kw) + + @hybridproperty + def directive(cls) -> _declared_directive[Any]: + # see mapping_api.rst for docstring + return _declared_directive # type: ignore + + @hybridproperty + def cascading(cls) -> _stateful_declared_attr[_T]: + # see mapping_api.rst for docstring + return cls._stateful(cascading=True) + + +class _stateful_declared_attr(declared_attr[_T]): + kw: Dict[str, Any] + + def __init__(self, **kw: Any): + self.kw = kw + + @hybridmethod + def _stateful(self, **kw: Any) -> _stateful_declared_attr[_T]: + new_kw = self.kw.copy() + new_kw.update(kw) + return _stateful_declared_attr(**new_kw) + + def __call__(self, fn: _DeclaredAttrDecorated[_T]) -> declared_attr[_T]: + return declared_attr(fn, **self.kw) + + +def declarative_mixin(cls: Type[_T]) -> Type[_T]: + """Mark a class as providing the feature of "declarative mixin". + + E.g.:: + + from sqlalchemy.orm import declared_attr + from sqlalchemy.orm import declarative_mixin + + + @declarative_mixin + class MyMixin: + + @declared_attr + def __tablename__(cls): + return cls.__name__.lower() + + __table_args__ = {"mysql_engine": "InnoDB"} + __mapper_args__ = {"always_refresh": True} + + id = Column(Integer, primary_key=True) + + + class MyModel(MyMixin, Base): + name = Column(String(1000)) + + The :func:`_orm.declarative_mixin` decorator currently does not modify + the given class in any way; it's current purpose is strictly to assist + the :ref:`Mypy plugin ` in being able to identify + SQLAlchemy declarative mixin classes when no other context is present. + + .. versionadded:: 1.4.6 + + .. legacy:: This api is considered legacy and will be deprecated in the next + SQLAlchemy version. + + .. seealso:: + + :ref:`orm_mixins_toplevel` + + :ref:`mypy_declarative_mixins` - in the + :ref:`Mypy plugin documentation ` + + """ # noqa: E501 + + return cls + + +def _setup_declarative_base(cls: Type[Any]) -> None: + if "metadata" in cls.__dict__: + metadata = cls.__dict__["metadata"] + else: + metadata = None + + if "type_annotation_map" in cls.__dict__: + type_annotation_map = cls.__dict__["type_annotation_map"] + else: + type_annotation_map = None + + reg = cls.__dict__.get("registry", None) + if reg is not None: + if not isinstance(reg, registry): + raise exc.InvalidRequestError( + "Declarative base class has a 'registry' attribute that is " + "not an instance of sqlalchemy.orm.registry()" + ) + elif type_annotation_map is not None: + raise exc.InvalidRequestError( + "Declarative base class has both a 'registry' attribute and a " + "type_annotation_map entry. Per-base type_annotation_maps " + "are not supported. Please apply the type_annotation_map " + "to this registry directly." + ) + + else: + reg = registry( + metadata=metadata, type_annotation_map=type_annotation_map + ) + cls.registry = reg + + cls._sa_registry = reg + + if "metadata" not in cls.__dict__: + cls.metadata = cls.registry.metadata + + if getattr(cls, "__init__", object.__init__) is object.__init__: + cls.__init__ = cls.registry.constructor + + +class MappedAsDataclass(metaclass=DCTransformDeclarative): + """Mixin class to indicate when mapping this class, also convert it to be + a dataclass. + + .. seealso:: + + :ref:`orm_declarative_native_dataclasses` - complete background + on SQLAlchemy native dataclass mapping + + .. versionadded:: 2.0 + + """ + + def __init_subclass__( + cls, + init: Union[_NoArg, bool] = _NoArg.NO_ARG, + repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 + eq: Union[_NoArg, bool] = _NoArg.NO_ARG, + order: Union[_NoArg, bool] = _NoArg.NO_ARG, + unsafe_hash: Union[_NoArg, bool] = _NoArg.NO_ARG, + match_args: Union[_NoArg, bool] = _NoArg.NO_ARG, + kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, + dataclass_callable: Union[ + _NoArg, Callable[..., Type[Any]] + ] = _NoArg.NO_ARG, + **kw: Any, + ) -> None: + apply_dc_transforms: _DataclassArguments = { + "init": init, + "repr": repr, + "eq": eq, + "order": order, + "unsafe_hash": unsafe_hash, + "match_args": match_args, + "kw_only": kw_only, + "dataclass_callable": dataclass_callable, + } + + current_transforms: _DataclassArguments + + if hasattr(cls, "_sa_apply_dc_transforms"): + current = cls._sa_apply_dc_transforms + + _ClassScanMapperConfig._assert_dc_arguments(current) + + cls._sa_apply_dc_transforms = current_transforms = { # type: ignore # noqa: E501 + k: current.get(k, _NoArg.NO_ARG) if v is _NoArg.NO_ARG else v + for k, v in apply_dc_transforms.items() + } + else: + cls._sa_apply_dc_transforms = current_transforms = ( + apply_dc_transforms + ) + + super().__init_subclass__(**kw) + + if not _is_mapped_class(cls): + new_anno = ( + _ClassScanMapperConfig._update_annotations_for_non_mapped_class + )(cls) + _ClassScanMapperConfig._apply_dataclasses_to_any_class( + current_transforms, cls, new_anno + ) + + +class DeclarativeBase( + # Inspectable is used only by the mypy plugin + inspection.Inspectable[InstanceState[Any]], + metaclass=DeclarativeAttributeIntercept, +): + """Base class used for declarative class definitions. + + The :class:`_orm.DeclarativeBase` allows for the creation of new + declarative bases in such a way that is compatible with type checkers:: + + + from sqlalchemy.orm import DeclarativeBase + + + class Base(DeclarativeBase): + pass + + The above ``Base`` class is now usable as the base for new declarative + mappings. The superclass makes use of the ``__init_subclass__()`` + method to set up new classes and metaclasses aren't used. + + When first used, the :class:`_orm.DeclarativeBase` class instantiates a new + :class:`_orm.registry` to be used with the base, assuming one was not + provided explicitly. The :class:`_orm.DeclarativeBase` class supports + class-level attributes which act as parameters for the construction of this + registry; such as to indicate a specific :class:`_schema.MetaData` + collection as well as a specific value for + :paramref:`_orm.registry.type_annotation_map`:: + + from typing_extensions import Annotated + + from sqlalchemy import BigInteger + from sqlalchemy import MetaData + from sqlalchemy import String + from sqlalchemy.orm import DeclarativeBase + + bigint = Annotated[int, "bigint"] + my_metadata = MetaData() + + + class Base(DeclarativeBase): + metadata = my_metadata + type_annotation_map = { + str: String().with_variant(String(255), "mysql", "mariadb"), + bigint: BigInteger(), + } + + Class-level attributes which may be specified include: + + :param metadata: optional :class:`_schema.MetaData` collection. + If a :class:`_orm.registry` is constructed automatically, this + :class:`_schema.MetaData` collection will be used to construct it. + Otherwise, the local :class:`_schema.MetaData` collection will supersede + that used by an existing :class:`_orm.registry` passed using the + :paramref:`_orm.DeclarativeBase.registry` parameter. + :param type_annotation_map: optional type annotation map that will be + passed to the :class:`_orm.registry` as + :paramref:`_orm.registry.type_annotation_map`. + :param registry: supply a pre-existing :class:`_orm.registry` directly. + + .. versionadded:: 2.0 Added :class:`.DeclarativeBase`, so that declarative + base classes may be constructed in such a way that is also recognized + by :pep:`484` type checkers. As a result, :class:`.DeclarativeBase` + and other subclassing-oriented APIs should be seen as + superseding previous "class returned by a function" APIs, namely + :func:`_orm.declarative_base` and :meth:`_orm.registry.generate_base`, + where the base class returned cannot be recognized by type checkers + without using plugins. + + **__init__ behavior** + + In a plain Python class, the base-most ``__init__()`` method in the class + hierarchy is ``object.__init__()``, which accepts no arguments. However, + when the :class:`_orm.DeclarativeBase` subclass is first declared, the + class is given an ``__init__()`` method that links to the + :paramref:`_orm.registry.constructor` constructor function, if no + ``__init__()`` method is already present; this is the usual declarative + constructor that will assign keyword arguments as attributes on the + instance, assuming those attributes are established at the class level + (i.e. are mapped, or are linked to a descriptor). This constructor is + **never accessed by a mapped class without being called explicitly via + super()**, as mapped classes are themselves given an ``__init__()`` method + directly which calls :paramref:`_orm.registry.constructor`, so in the + default case works independently of what the base-most ``__init__()`` + method does. + + .. versionchanged:: 2.0.1 :class:`_orm.DeclarativeBase` has a default + constructor that links to :paramref:`_orm.registry.constructor` by + default, so that calls to ``super().__init__()`` can access this + constructor. Previously, due to an implementation mistake, this default + constructor was missing, and calling ``super().__init__()`` would invoke + ``object.__init__()``. + + The :class:`_orm.DeclarativeBase` subclass may also declare an explicit + ``__init__()`` method which will replace the use of the + :paramref:`_orm.registry.constructor` function at this level:: + + class Base(DeclarativeBase): + def __init__(self, id=None): + self.id = id + + Mapped classes still will not invoke this constructor implicitly; it + remains only accessible by calling ``super().__init__()``:: + + class MyClass(Base): + def __init__(self, id=None, name=None): + self.name = name + super().__init__(id=id) + + Note that this is a different behavior from what functions like the legacy + :func:`_orm.declarative_base` would do; the base created by those functions + would always install :paramref:`_orm.registry.constructor` for + ``__init__()``. + + + """ + + if typing.TYPE_CHECKING: + + def _sa_inspect_type(self) -> Mapper[Self]: ... + + def _sa_inspect_instance(self) -> InstanceState[Self]: ... + + _sa_registry: ClassVar[_RegistryType] + + registry: ClassVar[_RegistryType] + """Refers to the :class:`_orm.registry` in use where new + :class:`_orm.Mapper` objects will be associated.""" + + metadata: ClassVar[MetaData] + """Refers to the :class:`_schema.MetaData` collection that will be used + for new :class:`_schema.Table` objects. + + .. seealso:: + + :ref:`orm_declarative_metadata` + + """ + + __name__: ClassVar[str] + + # this ideally should be Mapper[Self], but mypy as of 1.4.1 does not + # like it, and breaks the declared_attr_one test. Pyright/pylance is + # ok with it. + __mapper__: ClassVar[Mapper[Any]] + """The :class:`_orm.Mapper` object to which a particular class is + mapped. + + May also be acquired using :func:`_sa.inspect`, e.g. + ``inspect(klass)``. + + """ + + __table__: ClassVar[FromClause] + """The :class:`_sql.FromClause` to which a particular subclass is + mapped. + + This is usually an instance of :class:`_schema.Table` but may also + refer to other kinds of :class:`_sql.FromClause` such as + :class:`_sql.Subquery`, depending on how the class is mapped. + + .. seealso:: + + :ref:`orm_declarative_metadata` + + """ + + # pyright/pylance do not consider a classmethod a ClassVar so use Any + # https://github.com/microsoft/pylance-release/issues/3484 + __tablename__: Any + """String name to assign to the generated + :class:`_schema.Table` object, if not specified directly via + :attr:`_orm.DeclarativeBase.__table__`. + + .. seealso:: + + :ref:`orm_declarative_table` + + """ + + __mapper_args__: Any + """Dictionary of arguments which will be passed to the + :class:`_orm.Mapper` constructor. + + .. seealso:: + + :ref:`orm_declarative_mapper_options` + + """ + + __table_args__: Any + """A dictionary or tuple of arguments that will be passed to the + :class:`_schema.Table` constructor. See + :ref:`orm_declarative_table_configuration` + for background on the specific structure of this collection. + + .. seealso:: + + :ref:`orm_declarative_table_configuration` + + """ + + def __init__(self, **kw: Any): ... + + def __init_subclass__(cls, **kw: Any) -> None: + if DeclarativeBase in cls.__bases__: + _check_not_declarative(cls, DeclarativeBase) + _setup_declarative_base(cls) + else: + _as_declarative(cls._sa_registry, cls, cls.__dict__) + super().__init_subclass__(**kw) + + +def _check_not_declarative(cls: Type[Any], base: Type[Any]) -> None: + cls_dict = cls.__dict__ + if ( + "__table__" in cls_dict + and not ( + callable(cls_dict["__table__"]) + or hasattr(cls_dict["__table__"], "__get__") + ) + ) or isinstance(cls_dict.get("__tablename__", None), str): + raise exc.InvalidRequestError( + f"Cannot use {base.__name__!r} directly as a declarative base " + "class. Create a Base by creating a subclass of it." + ) + + +class DeclarativeBaseNoMeta( + # Inspectable is used only by the mypy plugin + inspection.Inspectable[InstanceState[Any]] +): + """Same as :class:`_orm.DeclarativeBase`, but does not use a metaclass + to intercept new attributes. + + The :class:`_orm.DeclarativeBaseNoMeta` base may be used when use of + custom metaclasses is desirable. + + .. versionadded:: 2.0 + + + """ + + _sa_registry: ClassVar[_RegistryType] + + registry: ClassVar[_RegistryType] + """Refers to the :class:`_orm.registry` in use where new + :class:`_orm.Mapper` objects will be associated.""" + + metadata: ClassVar[MetaData] + """Refers to the :class:`_schema.MetaData` collection that will be used + for new :class:`_schema.Table` objects. + + .. seealso:: + + :ref:`orm_declarative_metadata` + + """ + + # this ideally should be Mapper[Self], but mypy as of 1.4.1 does not + # like it, and breaks the declared_attr_one test. Pyright/pylance is + # ok with it. + __mapper__: ClassVar[Mapper[Any]] + """The :class:`_orm.Mapper` object to which a particular class is + mapped. + + May also be acquired using :func:`_sa.inspect`, e.g. + ``inspect(klass)``. + + """ + + __table__: Optional[FromClause] + """The :class:`_sql.FromClause` to which a particular subclass is + mapped. + + This is usually an instance of :class:`_schema.Table` but may also + refer to other kinds of :class:`_sql.FromClause` such as + :class:`_sql.Subquery`, depending on how the class is mapped. + + .. seealso:: + + :ref:`orm_declarative_metadata` + + """ + + if typing.TYPE_CHECKING: + + def _sa_inspect_type(self) -> Mapper[Self]: ... + + def _sa_inspect_instance(self) -> InstanceState[Self]: ... + + __tablename__: Any + """String name to assign to the generated + :class:`_schema.Table` object, if not specified directly via + :attr:`_orm.DeclarativeBase.__table__`. + + .. seealso:: + + :ref:`orm_declarative_table` + + """ + + __mapper_args__: Any + """Dictionary of arguments which will be passed to the + :class:`_orm.Mapper` constructor. + + .. seealso:: + + :ref:`orm_declarative_mapper_options` + + """ + + __table_args__: Any + """A dictionary or tuple of arguments that will be passed to the + :class:`_schema.Table` constructor. See + :ref:`orm_declarative_table_configuration` + for background on the specific structure of this collection. + + .. seealso:: + + :ref:`orm_declarative_table_configuration` + + """ + + def __init__(self, **kw: Any): ... + + def __init_subclass__(cls, **kw: Any) -> None: + if DeclarativeBaseNoMeta in cls.__bases__: + _check_not_declarative(cls, DeclarativeBaseNoMeta) + _setup_declarative_base(cls) + else: + _as_declarative(cls._sa_registry, cls, cls.__dict__) + super().__init_subclass__(**kw) + + +def add_mapped_attribute( + target: Type[_O], key: str, attr: MapperProperty[Any] +) -> None: + """Add a new mapped attribute to an ORM mapped class. + + E.g.:: + + add_mapped_attribute(User, "addresses", relationship(Address)) + + This may be used for ORM mappings that aren't using a declarative + metaclass that intercepts attribute set operations. + + .. versionadded:: 2.0 + + + """ + _add_attribute(target, key, attr) + + +def declarative_base( + *, + metadata: Optional[MetaData] = None, + mapper: Optional[Callable[..., Mapper[Any]]] = None, + cls: Type[Any] = object, + name: str = "Base", + class_registry: Optional[clsregistry._ClsRegistryType] = None, + type_annotation_map: Optional[_TypeAnnotationMapType] = None, + constructor: Callable[..., None] = _declarative_constructor, + metaclass: Type[Any] = DeclarativeMeta, +) -> Any: + r"""Construct a base class for declarative class definitions. + + The new base class will be given a metaclass that produces + appropriate :class:`~sqlalchemy.schema.Table` objects and makes + the appropriate :class:`_orm.Mapper` calls based on the + information provided declaratively in the class and any subclasses + of the class. + + .. versionchanged:: 2.0 Note that the :func:`_orm.declarative_base` + function is superseded by the new :class:`_orm.DeclarativeBase` class, + which generates a new "base" class using subclassing, rather than + return value of a function. This allows an approach that is compatible + with :pep:`484` typing tools. + + The :func:`_orm.declarative_base` function is a shorthand version + of using the :meth:`_orm.registry.generate_base` + method. That is, the following:: + + from sqlalchemy.orm import declarative_base + + Base = declarative_base() + + Is equivalent to:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + Base = mapper_registry.generate_base() + + See the docstring for :class:`_orm.registry` + and :meth:`_orm.registry.generate_base` + for more details. + + .. versionchanged:: 1.4 The :func:`_orm.declarative_base` + function is now a specialization of the more generic + :class:`_orm.registry` class. The function also moves to the + ``sqlalchemy.orm`` package from the ``declarative.ext`` package. + + + :param metadata: + An optional :class:`~sqlalchemy.schema.MetaData` instance. All + :class:`~sqlalchemy.schema.Table` objects implicitly declared by + subclasses of the base will share this MetaData. A MetaData instance + will be created if none is provided. The + :class:`~sqlalchemy.schema.MetaData` instance will be available via the + ``metadata`` attribute of the generated declarative base class. + + :param mapper: + An optional callable, defaults to :class:`_orm.Mapper`. Will + be used to map subclasses to their Tables. + + :param cls: + Defaults to :class:`object`. A type to use as the base for the generated + declarative base class. May be a class or tuple of classes. + + :param name: + Defaults to ``Base``. The display name for the generated + class. Customizing this is not required, but can improve clarity in + tracebacks and debugging. + + :param constructor: + Specify the implementation for the ``__init__`` function on a mapped + class that has no ``__init__`` of its own. Defaults to an + implementation that assigns \**kwargs for declared + fields and relationships to an instance. If ``None`` is supplied, + no __init__ will be provided and construction will fall back to + cls.__init__ by way of the normal Python semantics. + + :param class_registry: optional dictionary that will serve as the + registry of class names-> mapped classes when string names + are used to identify classes inside of :func:`_orm.relationship` + and others. Allows two or more declarative base classes + to share the same registry of class names for simplified + inter-base relationships. + + :param type_annotation_map: optional dictionary of Python types to + SQLAlchemy :class:`_types.TypeEngine` classes or instances. This + is used exclusively by the :class:`_orm.MappedColumn` construct + to produce column types based on annotations within the + :class:`_orm.Mapped` type. + + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`orm_declarative_mapped_column_type_map` + + :param metaclass: + Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ + compatible callable to use as the meta type of the generated + declarative base class. + + .. seealso:: + + :class:`_orm.registry` + + """ + + return registry( + metadata=metadata, + class_registry=class_registry, + constructor=constructor, + type_annotation_map=type_annotation_map, + ).generate_base( + mapper=mapper, + cls=cls, + name=name, + metaclass=metaclass, + ) + + +class registry: + """Generalized registry for mapping classes. + + The :class:`_orm.registry` serves as the basis for maintaining a collection + of mappings, and provides configurational hooks used to map classes. + + The three general kinds of mappings supported are Declarative Base, + Declarative Decorator, and Imperative Mapping. All of these mapping + styles may be used interchangeably: + + * :meth:`_orm.registry.generate_base` returns a new declarative base + class, and is the underlying implementation of the + :func:`_orm.declarative_base` function. + + * :meth:`_orm.registry.mapped` provides a class decorator that will + apply declarative mapping to a class without the use of a declarative + base class. + + * :meth:`_orm.registry.map_imperatively` will produce a + :class:`_orm.Mapper` for a class without scanning the class for + declarative class attributes. This method suits the use case historically + provided by the ``sqlalchemy.orm.mapper()`` classical mapping function, + which is removed as of SQLAlchemy 2.0. + + .. versionadded:: 1.4 + + .. seealso:: + + :ref:`orm_mapping_classes_toplevel` - overview of class mapping + styles. + + """ + + _class_registry: clsregistry._ClsRegistryType + _managers: weakref.WeakKeyDictionary[ClassManager[Any], Literal[True]] + _non_primary_mappers: weakref.WeakKeyDictionary[Mapper[Any], Literal[True]] + metadata: MetaData + constructor: CallableReference[Callable[..., None]] + type_annotation_map: _MutableTypeAnnotationMapType + _dependents: Set[_RegistryType] + _dependencies: Set[_RegistryType] + _new_mappers: bool + + def __init__( + self, + *, + metadata: Optional[MetaData] = None, + class_registry: Optional[clsregistry._ClsRegistryType] = None, + type_annotation_map: Optional[_TypeAnnotationMapType] = None, + constructor: Callable[..., None] = _declarative_constructor, + ): + r"""Construct a new :class:`_orm.registry` + + :param metadata: + An optional :class:`_schema.MetaData` instance. All + :class:`_schema.Table` objects generated using declarative + table mapping will make use of this :class:`_schema.MetaData` + collection. If this argument is left at its default of ``None``, + a blank :class:`_schema.MetaData` collection is created. + + :param constructor: + Specify the implementation for the ``__init__`` function on a mapped + class that has no ``__init__`` of its own. Defaults to an + implementation that assigns \**kwargs for declared + fields and relationships to an instance. If ``None`` is supplied, + no __init__ will be provided and construction will fall back to + cls.__init__ by way of the normal Python semantics. + + :param class_registry: optional dictionary that will serve as the + registry of class names-> mapped classes when string names + are used to identify classes inside of :func:`_orm.relationship` + and others. Allows two or more declarative base classes + to share the same registry of class names for simplified + inter-base relationships. + + :param type_annotation_map: optional dictionary of Python types to + SQLAlchemy :class:`_types.TypeEngine` classes or instances. + The provided dict will update the default type mapping. This + is used exclusively by the :class:`_orm.MappedColumn` construct + to produce column types based on annotations within the + :class:`_orm.Mapped` type. + + .. versionadded:: 2.0 + + .. seealso:: + + :ref:`orm_declarative_mapped_column_type_map` + + + """ + lcl_metadata = metadata or MetaData() + + if class_registry is None: + class_registry = weakref.WeakValueDictionary() + + self._class_registry = class_registry + self._managers = weakref.WeakKeyDictionary() + self._non_primary_mappers = weakref.WeakKeyDictionary() + self.metadata = lcl_metadata + self.constructor = constructor + self.type_annotation_map = {} + if type_annotation_map is not None: + self.update_type_annotation_map(type_annotation_map) + self._dependents = set() + self._dependencies = set() + + self._new_mappers = False + + with mapperlib._CONFIGURE_MUTEX: + mapperlib._mapper_registries[self] = True + + def update_type_annotation_map( + self, + type_annotation_map: _TypeAnnotationMapType, + ) -> None: + """update the :paramref:`_orm.registry.type_annotation_map` with new + values.""" + + self.type_annotation_map.update( + { + de_optionalize_union_types(typ): sqltype + for typ, sqltype in type_annotation_map.items() + } + ) + + def _resolve_type( + self, python_type: _MatchedOnType, _do_fallbacks: bool = False + ) -> Optional[sqltypes.TypeEngine[Any]]: + python_type_type: Type[Any] + search: Iterable[Tuple[_MatchedOnType, Type[Any]]] + + if is_generic(python_type): + if is_literal(python_type): + python_type_type = python_type # type: ignore[assignment] + + search = ( + (python_type, python_type_type), + *((lt, python_type_type) for lt in LITERAL_TYPES), + ) + else: + python_type_type = python_type.__origin__ + search = ((python_type, python_type_type),) + elif isinstance(python_type, type): + python_type_type = python_type + search = ((pt, pt) for pt in python_type_type.__mro__) + else: + python_type_type = python_type # type: ignore[assignment] + search = ((python_type, python_type_type),) + + for pt, flattened in search: + # we search through full __mro__ for types. however... + sql_type = self.type_annotation_map.get(pt) + if sql_type is None: + sql_type = sqltypes._type_map_get(pt) # type: ignore # noqa: E501 + + if sql_type is not None: + sql_type_inst = sqltypes.to_instance(sql_type) + + # ... this additional step will reject most + # type -> supertype matches, such as if we had + # a MyInt(int) subclass. note also we pass NewType() + # here directly; these always have to be in the + # type_annotation_map to be useful + resolved_sql_type = sql_type_inst._resolve_for_python_type( + python_type_type, + pt, + flattened, + ) + if resolved_sql_type is not None: + return resolved_sql_type + + # 2.0 fallbacks + if _do_fallbacks: + python_type_to_check: Any = None + kind = None + if is_pep695(python_type): + # NOTE: assume there aren't type alias types of new types. + python_type_to_check = python_type + while is_pep695(python_type_to_check) and not is_pep593( + python_type_to_check + ): + python_type_to_check = python_type_to_check.__value__ + python_type_to_check = de_optionalize_union_types( + python_type_to_check + ) + kind = "pep-695 type" + if is_newtype(python_type): + python_type_to_check = flatten_newtype(python_type) + kind = "NewType" + + if python_type_to_check is not None: + res_after_fallback = self._resolve_type( + python_type_to_check, False + ) + if res_after_fallback is not None: + assert kind is not None + if kind == "pep-695 type": + warn_deprecated( + f"Matching to {kind} '{python_type}' in " + "a recursive " + "fashion without the recursed type being present " + "in the type_annotation_map is deprecated; add " + "this type or its recursed value to " + "the type_annotation_map to allow it to match " + "explicitly.", + "2.0", + ) + else: + warn_deprecated( + f"Matching the provided {kind} '{python_type}' on " + "its resolved value without matching it in the " + "type_annotation_map is deprecated; add this " + "type to " + "the type_annotation_map to allow it to match " + "explicitly.", + "2.0", + ) + return res_after_fallback + + return None + + @property + def mappers(self) -> FrozenSet[Mapper[Any]]: + """read only collection of all :class:`_orm.Mapper` objects.""" + + return frozenset(manager.mapper for manager in self._managers).union( + self._non_primary_mappers + ) + + def _set_depends_on(self, registry: RegistryType) -> None: + if registry is self: + return + registry._dependents.add(self) + self._dependencies.add(registry) + + def _flag_new_mapper(self, mapper: Mapper[Any]) -> None: + mapper._ready_for_configure = True + if self._new_mappers: + return + + for reg in self._recurse_with_dependents({self}): + reg._new_mappers = True + + @classmethod + def _recurse_with_dependents( + cls, registries: Set[RegistryType] + ) -> Iterator[RegistryType]: + todo = registries + done = set() + while todo: + reg = todo.pop() + done.add(reg) + + # if yielding would remove dependents, make sure we have + # them before + todo.update(reg._dependents.difference(done)) + yield reg + + # if yielding would add dependents, make sure we have them + # after + todo.update(reg._dependents.difference(done)) + + @classmethod + def _recurse_with_dependencies( + cls, registries: Set[RegistryType] + ) -> Iterator[RegistryType]: + todo = registries + done = set() + while todo: + reg = todo.pop() + done.add(reg) + + # if yielding would remove dependencies, make sure we have + # them before + todo.update(reg._dependencies.difference(done)) + + yield reg + + # if yielding would remove dependencies, make sure we have + # them before + todo.update(reg._dependencies.difference(done)) + + def _mappers_to_configure(self) -> Iterator[Mapper[Any]]: + return itertools.chain( + ( + manager.mapper + for manager in list(self._managers) + if manager.is_mapped + and not manager.mapper.configured + and manager.mapper._ready_for_configure + ), + ( + npm + for npm in list(self._non_primary_mappers) + if not npm.configured and npm._ready_for_configure + ), + ) + + def _add_non_primary_mapper(self, np_mapper: Mapper[Any]) -> None: + self._non_primary_mappers[np_mapper] = True + + def _dispose_cls(self, cls: Type[_O]) -> None: + clsregistry.remove_class(cls.__name__, cls, self._class_registry) + + def _add_manager(self, manager: ClassManager[Any]) -> None: + self._managers[manager] = True + if manager.is_mapped: + raise exc.ArgumentError( + "Class '%s' already has a primary mapper defined. " + % manager.class_ + ) + assert manager.registry is None + manager.registry = self + + def configure(self, cascade: bool = False) -> None: + """Configure all as-yet unconfigured mappers in this + :class:`_orm.registry`. + + The configure step is used to reconcile and initialize the + :func:`_orm.relationship` linkages between mapped classes, as well as + to invoke configuration events such as the + :meth:`_orm.MapperEvents.before_configured` and + :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM + extensions or user-defined extension hooks. + + If one or more mappers in this registry contain + :func:`_orm.relationship` constructs that refer to mapped classes in + other registries, this registry is said to be *dependent* on those + registries. In order to configure those dependent registries + automatically, the :paramref:`_orm.registry.configure.cascade` flag + should be set to ``True``. Otherwise, if they are not configured, an + exception will be raised. The rationale behind this behavior is to + allow an application to programmatically invoke configuration of + registries while controlling whether or not the process implicitly + reaches other registries. + + As an alternative to invoking :meth:`_orm.registry.configure`, the ORM + function :func:`_orm.configure_mappers` function may be used to ensure + configuration is complete for all :class:`_orm.registry` objects in + memory. This is generally simpler to use and also predates the usage of + :class:`_orm.registry` objects overall. However, this function will + impact all mappings throughout the running Python process and may be + more memory/time consuming for an application that has many registries + in use for different purposes that may not be needed immediately. + + .. seealso:: + + :func:`_orm.configure_mappers` + + + .. versionadded:: 1.4.0b2 + + """ + mapperlib._configure_registries({self}, cascade=cascade) + + def dispose(self, cascade: bool = False) -> None: + """Dispose of all mappers in this :class:`_orm.registry`. + + After invocation, all the classes that were mapped within this registry + will no longer have class instrumentation associated with them. This + method is the per-:class:`_orm.registry` analogue to the + application-wide :func:`_orm.clear_mappers` function. + + If this registry contains mappers that are dependencies of other + registries, typically via :func:`_orm.relationship` links, then those + registries must be disposed as well. When such registries exist in + relation to this one, their :meth:`_orm.registry.dispose` method will + also be called, if the :paramref:`_orm.registry.dispose.cascade` flag + is set to ``True``; otherwise, an error is raised if those registries + were not already disposed. + + .. versionadded:: 1.4.0b2 + + .. seealso:: + + :func:`_orm.clear_mappers` + + """ + + mapperlib._dispose_registries({self}, cascade=cascade) + + def _dispose_manager_and_mapper(self, manager: ClassManager[Any]) -> None: + if "mapper" in manager.__dict__: + mapper = manager.mapper + + mapper._set_dispose_flags() + + class_ = manager.class_ + self._dispose_cls(class_) + instrumentation._instrumentation_factory.unregister(class_) + + def generate_base( + self, + mapper: Optional[Callable[..., Mapper[Any]]] = None, + cls: Type[Any] = object, + name: str = "Base", + metaclass: Type[Any] = DeclarativeMeta, + ) -> Any: + """Generate a declarative base class. + + Classes that inherit from the returned class object will be + automatically mapped using declarative mapping. + + E.g.:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + + Base = mapper_registry.generate_base() + + + class MyClass(Base): + __tablename__ = "my_table" + id = Column(Integer, primary_key=True) + + The above dynamically generated class is equivalent to the + non-dynamic example below:: + + from sqlalchemy.orm import registry + from sqlalchemy.orm.decl_api import DeclarativeMeta + + mapper_registry = registry() + + + class Base(metaclass=DeclarativeMeta): + __abstract__ = True + registry = mapper_registry + metadata = mapper_registry.metadata + + __init__ = mapper_registry.constructor + + .. versionchanged:: 2.0 Note that the + :meth:`_orm.registry.generate_base` method is superseded by the new + :class:`_orm.DeclarativeBase` class, which generates a new "base" + class using subclassing, rather than return value of a function. + This allows an approach that is compatible with :pep:`484` typing + tools. + + The :meth:`_orm.registry.generate_base` method provides the + implementation for the :func:`_orm.declarative_base` function, which + creates the :class:`_orm.registry` and base class all at once. + + See the section :ref:`orm_declarative_mapping` for background and + examples. + + :param mapper: + An optional callable, defaults to :class:`_orm.Mapper`. + This function is used to generate new :class:`_orm.Mapper` objects. + + :param cls: + Defaults to :class:`object`. A type to use as the base for the + generated declarative base class. May be a class or tuple of classes. + + :param name: + Defaults to ``Base``. The display name for the generated + class. Customizing this is not required, but can improve clarity in + tracebacks and debugging. + + :param metaclass: + Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ + compatible callable to use as the meta type of the generated + declarative base class. + + .. seealso:: + + :ref:`orm_declarative_mapping` + + :func:`_orm.declarative_base` + + """ + metadata = self.metadata + + bases = not isinstance(cls, tuple) and (cls,) or cls + + class_dict: Dict[str, Any] = dict(registry=self, metadata=metadata) + if isinstance(cls, type): + class_dict["__doc__"] = cls.__doc__ + + if self.constructor is not None: + class_dict["__init__"] = self.constructor + + class_dict["__abstract__"] = True + if mapper: + class_dict["__mapper_cls__"] = mapper + + if hasattr(cls, "__class_getitem__"): + + def __class_getitem__(cls: Type[_T], key: Any) -> Type[_T]: + # allow generic classes in py3.9+ + return cls + + class_dict["__class_getitem__"] = __class_getitem__ + + return metaclass(name, bases, class_dict) + + @compat_typing.dataclass_transform( + field_specifiers=( + MappedColumn, + RelationshipProperty, + Composite, + Synonym, + mapped_column, + relationship, + composite, + synonym, + deferred, + ), + ) + @overload + def mapped_as_dataclass(self, __cls: Type[_O]) -> Type[_O]: ... + + @overload + def mapped_as_dataclass( + self, + __cls: Literal[None] = ..., + *, + init: Union[_NoArg, bool] = ..., + repr: Union[_NoArg, bool] = ..., # noqa: A002 + eq: Union[_NoArg, bool] = ..., + order: Union[_NoArg, bool] = ..., + unsafe_hash: Union[_NoArg, bool] = ..., + match_args: Union[_NoArg, bool] = ..., + kw_only: Union[_NoArg, bool] = ..., + dataclass_callable: Union[_NoArg, Callable[..., Type[Any]]] = ..., + ) -> Callable[[Type[_O]], Type[_O]]: ... + + def mapped_as_dataclass( + self, + __cls: Optional[Type[_O]] = None, + *, + init: Union[_NoArg, bool] = _NoArg.NO_ARG, + repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 + eq: Union[_NoArg, bool] = _NoArg.NO_ARG, + order: Union[_NoArg, bool] = _NoArg.NO_ARG, + unsafe_hash: Union[_NoArg, bool] = _NoArg.NO_ARG, + match_args: Union[_NoArg, bool] = _NoArg.NO_ARG, + kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, + dataclass_callable: Union[ + _NoArg, Callable[..., Type[Any]] + ] = _NoArg.NO_ARG, + ) -> Union[Type[_O], Callable[[Type[_O]], Type[_O]]]: + """Class decorator that will apply the Declarative mapping process + to a given class, and additionally convert the class to be a + Python dataclass. + + .. seealso:: + + :ref:`orm_declarative_native_dataclasses` - complete background + on SQLAlchemy native dataclass mapping + + :func:`_orm.mapped_as_dataclass` - functional version that may + provide better compatibility with mypy + + .. versionadded:: 2.0 + + + """ + + def decorate(cls: Type[_O]) -> Type[_O]: + setattr( + cls, + "_sa_apply_dc_transforms", + { + "init": init, + "repr": repr, + "eq": eq, + "order": order, + "unsafe_hash": unsafe_hash, + "match_args": match_args, + "kw_only": kw_only, + "dataclass_callable": dataclass_callable, + }, + ) + _as_declarative(self, cls, cls.__dict__) + return cls + + if __cls: + return decorate(__cls) + else: + return decorate + + def mapped(self, cls: Type[_O]) -> Type[_O]: + """Class decorator that will apply the Declarative mapping process + to a given class. + + E.g.:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + + + @mapper_registry.mapped + class Foo: + __tablename__ = "some_table" + + id = Column(Integer, primary_key=True) + name = Column(String) + + See the section :ref:`orm_declarative_mapping` for complete + details and examples. + + :param cls: class to be mapped. + + :return: the class that was passed. + + .. seealso:: + + :ref:`orm_declarative_mapping` + + :meth:`_orm.registry.generate_base` - generates a base class + that will apply Declarative mapping to subclasses automatically + using a Python metaclass. + + .. seealso:: + + :meth:`_orm.registry.mapped_as_dataclass` + + """ + _as_declarative(self, cls, cls.__dict__) + return cls + + def as_declarative_base(self, **kw: Any) -> Callable[[Type[_T]], Type[_T]]: + """ + Class decorator which will invoke + :meth:`_orm.registry.generate_base` + for a given base class. + + E.g.:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + + + @mapper_registry.as_declarative_base() + class Base: + @declared_attr + def __tablename__(cls): + return cls.__name__.lower() + + id = Column(Integer, primary_key=True) + + + class MyMappedClass(Base): ... + + All keyword arguments passed to + :meth:`_orm.registry.as_declarative_base` are passed + along to :meth:`_orm.registry.generate_base`. + + """ + + def decorate(cls: Type[_T]) -> Type[_T]: + kw["cls"] = cls + kw["name"] = cls.__name__ + return self.generate_base(**kw) # type: ignore + + return decorate + + def map_declaratively(self, cls: Type[_O]) -> Mapper[_O]: + """Map a class declaratively. + + In this form of mapping, the class is scanned for mapping information, + including for columns to be associated with a table, and/or an + actual table object. + + Returns the :class:`_orm.Mapper` object. + + E.g.:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + + + class Foo: + __tablename__ = "some_table" + + id = Column(Integer, primary_key=True) + name = Column(String) + + + mapper = mapper_registry.map_declaratively(Foo) + + This function is more conveniently invoked indirectly via either the + :meth:`_orm.registry.mapped` class decorator or by subclassing a + declarative metaclass generated from + :meth:`_orm.registry.generate_base`. + + See the section :ref:`orm_declarative_mapping` for complete + details and examples. + + :param cls: class to be mapped. + + :return: a :class:`_orm.Mapper` object. + + .. seealso:: + + :ref:`orm_declarative_mapping` + + :meth:`_orm.registry.mapped` - more common decorator interface + to this function. + + :meth:`_orm.registry.map_imperatively` + + """ + _as_declarative(self, cls, cls.__dict__) + return cls.__mapper__ # type: ignore + + def map_imperatively( + self, + class_: Type[_O], + local_table: Optional[FromClause] = None, + **kw: Any, + ) -> Mapper[_O]: + r"""Map a class imperatively. + + In this form of mapping, the class is not scanned for any mapping + information. Instead, all mapping constructs are passed as + arguments. + + This method is intended to be fully equivalent to the now-removed + SQLAlchemy ``mapper()`` function, except that it's in terms of + a particular registry. + + E.g.:: + + from sqlalchemy.orm import registry + + mapper_registry = registry() + + my_table = Table( + "my_table", + mapper_registry.metadata, + Column("id", Integer, primary_key=True), + ) + + + class MyClass: + pass + + + mapper_registry.map_imperatively(MyClass, my_table) + + See the section :ref:`orm_imperative_mapping` for complete background + and usage examples. + + :param class\_: The class to be mapped. Corresponds to the + :paramref:`_orm.Mapper.class_` parameter. + + :param local_table: the :class:`_schema.Table` or other + :class:`_sql.FromClause` object that is the subject of the mapping. + Corresponds to the + :paramref:`_orm.Mapper.local_table` parameter. + + :param \**kw: all other keyword arguments are passed to the + :class:`_orm.Mapper` constructor directly. + + .. seealso:: + + :ref:`orm_imperative_mapping` + + :ref:`orm_declarative_mapping` + + """ + return _mapper(self, class_, local_table, kw) + + +RegistryType = registry + +if not TYPE_CHECKING: + # allow for runtime type resolution of ``ClassVar[_RegistryType]`` + _RegistryType = registry # noqa + + +def as_declarative(**kw: Any) -> Callable[[Type[_T]], Type[_T]]: + """ + Class decorator which will adapt a given class into a + :func:`_orm.declarative_base`. + + This function makes use of the :meth:`_orm.registry.as_declarative_base` + method, by first creating a :class:`_orm.registry` automatically + and then invoking the decorator. + + E.g.:: + + from sqlalchemy.orm import as_declarative + + + @as_declarative() + class Base: + @declared_attr + def __tablename__(cls): + return cls.__name__.lower() + + id = Column(Integer, primary_key=True) + + + class MyMappedClass(Base): ... + + .. seealso:: + + :meth:`_orm.registry.as_declarative_base` + + """ + metadata, class_registry = ( + kw.pop("metadata", None), + kw.pop("class_registry", None), + ) + + return registry( + metadata=metadata, class_registry=class_registry + ).as_declarative_base(**kw) + + +@compat_typing.dataclass_transform( + field_specifiers=( + MappedColumn, + RelationshipProperty, + Composite, + Synonym, + mapped_column, + relationship, + composite, + synonym, + deferred, + ), +) +def mapped_as_dataclass( + registry: RegistryType, + *, + init: Union[_NoArg, bool] = _NoArg.NO_ARG, + repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 + eq: Union[_NoArg, bool] = _NoArg.NO_ARG, + order: Union[_NoArg, bool] = _NoArg.NO_ARG, + unsafe_hash: Union[_NoArg, bool] = _NoArg.NO_ARG, + match_args: Union[_NoArg, bool] = _NoArg.NO_ARG, + kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, + dataclass_callable: Union[ + _NoArg, Callable[..., Type[Any]] + ] = _NoArg.NO_ARG, +) -> Callable[[Type[_O]], Type[_O]]: + """Standalone function form of :meth:`_orm.registry.mapped_as_dataclass` + which may have better compatibility with mypy. + + The :class:`_orm.registry` is passed as the first argument to the + decorator. + + e.g.:: + + from sqlalchemy.orm import Mapped + from sqlalchemy.orm import mapped_as_dataclass + from sqlalchemy.orm import mapped_column + from sqlalchemy.orm import registry + + some_registry = registry() + + + @mapped_as_dataclass(some_registry) + class Relationships: + __tablename__ = "relationships" + + entity_id1: Mapped[int] = mapped_column(primary_key=True) + entity_id2: Mapped[int] = mapped_column(primary_key=True) + level: Mapped[int] = mapped_column(Integer) + + .. versionadded:: 2.0.44 + + """ + return registry.mapped_as_dataclass( + init=init, + repr=repr, + eq=eq, + order=order, + unsafe_hash=unsafe_hash, + match_args=match_args, + kw_only=kw_only, + dataclass_callable=dataclass_callable, + ) + + +@inspection._inspects( + DeclarativeMeta, DeclarativeBase, DeclarativeAttributeIntercept +) +def _inspect_decl_meta(cls: Type[Any]) -> Optional[Mapper[Any]]: + mp: Optional[Mapper[Any]] = _inspect_mapped_class(cls) + if mp is None: + if _DeferredMapperConfig.has_cls(cls): + _DeferredMapperConfig.raise_unmapped_for_cls(cls) + return mp diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_base.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5c304693dd6d838e633b534b9d1c237eb53106a9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/decl_base.py @@ -0,0 +1,2192 @@ +# orm/decl_base.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Internal implementation for declarative.""" + +from __future__ import annotations + +import collections +import dataclasses +import re +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import Iterable +from typing import List +from typing import Mapping +from typing import NamedTuple +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import attributes +from . import clsregistry +from . import exc as orm_exc +from . import instrumentation +from . import mapperlib +from ._typing import _O +from ._typing import attr_is_internal_proxy +from .attributes import InstrumentedAttribute +from .attributes import QueryableAttribute +from .base import _is_mapped_class +from .base import InspectionAttr +from .descriptor_props import CompositeProperty +from .descriptor_props import SynonymProperty +from .interfaces import _AttributeOptions +from .interfaces import _DCAttributeOptions +from .interfaces import _IntrospectsAnnotations +from .interfaces import _MappedAttribute +from .interfaces import _MapsColumns +from .interfaces import MapperProperty +from .mapper import Mapper +from .properties import ColumnProperty +from .properties import MappedColumn +from .util import _extract_mapped_subtype +from .util import _is_mapped_annotation +from .util import class_mapper +from .util import de_stringify_annotation +from .. import event +from .. import exc +from .. import util +from ..sql import expression +from ..sql.base import _NoArg +from ..sql.schema import Column +from ..sql.schema import Table +from ..util import topological +from ..util.typing import _AnnotationScanType +from ..util.typing import get_args +from ..util.typing import is_fwd_ref +from ..util.typing import is_literal +from ..util.typing import Protocol +from ..util.typing import TypedDict + +if TYPE_CHECKING: + from ._typing import _ClassDict + from ._typing import _RegistryType + from .base import Mapped + from .decl_api import declared_attr + from .instrumentation import ClassManager + from ..sql.elements import NamedColumn + from ..sql.schema import MetaData + from ..sql.selectable import FromClause + +_T = TypeVar("_T", bound=Any) + +_MapperKwArgs = Mapping[str, Any] +_TableArgsType = Union[Tuple[Any, ...], Dict[str, Any]] + + +class MappedClassProtocol(Protocol[_O]): + """A protocol representing a SQLAlchemy mapped class. + + The protocol is generic on the type of class, use + ``MappedClassProtocol[Any]`` to allow any mapped class. + """ + + __name__: str + __mapper__: Mapper[_O] + __table__: FromClause + + def __call__(self, **kw: Any) -> _O: ... + + +class _DeclMappedClassProtocol(MappedClassProtocol[_O], Protocol): + "Internal more detailed version of ``MappedClassProtocol``." + + metadata: MetaData + __tablename__: str + __mapper_args__: _MapperKwArgs + __table_args__: Optional[_TableArgsType] + + _sa_apply_dc_transforms: Optional[_DataclassArguments] + + def __declare_first__(self) -> None: ... + + def __declare_last__(self) -> None: ... + + +class _DataclassArguments(TypedDict): + init: Union[_NoArg, bool] + repr: Union[_NoArg, bool] + eq: Union[_NoArg, bool] + order: Union[_NoArg, bool] + unsafe_hash: Union[_NoArg, bool] + match_args: Union[_NoArg, bool] + kw_only: Union[_NoArg, bool] + dataclass_callable: Union[_NoArg, Callable[..., Type[Any]]] + + +def _declared_mapping_info( + cls: Type[Any], +) -> Optional[Union[_DeferredMapperConfig, Mapper[Any]]]: + # deferred mapping + if _DeferredMapperConfig.has_cls(cls): + return _DeferredMapperConfig.config_for_cls(cls) + # regular mapping + elif _is_mapped_class(cls): + return class_mapper(cls, configure=False) + else: + return None + + +def _is_supercls_for_inherits(cls: Type[Any]) -> bool: + """return True if this class will be used as a superclass to set in + 'inherits'. + + This includes deferred mapper configs that aren't mapped yet, however does + not include classes with _sa_decl_prepare_nocascade (e.g. + ``AbstractConcreteBase``); these concrete-only classes are not set up as + "inherits" until after mappers are configured using + mapper._set_concrete_base() + + """ + if _DeferredMapperConfig.has_cls(cls): + return not _get_immediate_cls_attr( + cls, "_sa_decl_prepare_nocascade", strict=True + ) + # regular mapping + elif _is_mapped_class(cls): + return True + else: + return False + + +def _resolve_for_abstract_or_classical(cls: Type[Any]) -> Optional[Type[Any]]: + if cls is object: + return None + + sup: Optional[Type[Any]] + + if cls.__dict__.get("__abstract__", False): + for base_ in cls.__bases__: + sup = _resolve_for_abstract_or_classical(base_) + if sup is not None: + return sup + else: + return None + else: + clsmanager = _dive_for_cls_manager(cls) + + if clsmanager: + return clsmanager.class_ + else: + return cls + + +def _get_immediate_cls_attr( + cls: Type[Any], attrname: str, strict: bool = False +) -> Optional[Any]: + """return an attribute of the class that is either present directly + on the class, e.g. not on a superclass, or is from a superclass but + this superclass is a non-mapped mixin, that is, not a descendant of + the declarative base and is also not classically mapped. + + This is used to detect attributes that indicate something about + a mapped class independently from any mapped classes that it may + inherit from. + + """ + + # the rules are different for this name than others, + # make sure we've moved it out. transitional + assert attrname != "__abstract__" + + if not issubclass(cls, object): + return None + + if attrname in cls.__dict__: + return getattr(cls, attrname) + + for base in cls.__mro__[1:]: + _is_classical_inherits = _dive_for_cls_manager(base) is not None + + if attrname in base.__dict__ and ( + base is cls + or ( + (base in cls.__bases__ if strict else True) + and not _is_classical_inherits + ) + ): + return getattr(base, attrname) + else: + return None + + +def _dive_for_cls_manager(cls: Type[_O]) -> Optional[ClassManager[_O]]: + # because the class manager registration is pluggable, + # we need to do the search for every class in the hierarchy, + # rather than just a simple "cls._sa_class_manager" + + for base in cls.__mro__: + manager: Optional[ClassManager[_O]] = attributes.opt_manager_of_class( + base + ) + if manager: + return manager + return None + + +def _as_declarative( + registry: _RegistryType, cls: Type[Any], dict_: _ClassDict +) -> Optional[_MapperConfig]: + # declarative scans the class for attributes. no table or mapper + # args passed separately. + return _MapperConfig.setup_mapping(registry, cls, dict_, None, {}) + + +def _mapper( + registry: _RegistryType, + cls: Type[_O], + table: Optional[FromClause], + mapper_kw: _MapperKwArgs, +) -> Mapper[_O]: + _ImperativeMapperConfig(registry, cls, table, mapper_kw) + return cast("MappedClassProtocol[_O]", cls).__mapper__ + + +@util.preload_module("sqlalchemy.orm.decl_api") +def _is_declarative_props(obj: Any) -> bool: + _declared_attr_common = util.preloaded.orm_decl_api._declared_attr_common + + return isinstance(obj, (_declared_attr_common, util.classproperty)) + + +def _check_declared_props_nocascade( + obj: Any, name: str, cls: Type[_O] +) -> bool: + if _is_declarative_props(obj): + if getattr(obj, "_cascading", False): + util.warn( + "@declared_attr.cascading is not supported on the %s " + "attribute on class %s. This attribute invokes for " + "subclasses in any case." % (name, cls) + ) + return True + else: + return False + + +class _MapperConfig: + __slots__ = ( + "cls", + "classname", + "properties", + "declared_attr_reg", + "__weakref__", + ) + + cls: Type[Any] + classname: str + properties: util.OrderedDict[ + str, + Union[ + Sequence[NamedColumn[Any]], NamedColumn[Any], MapperProperty[Any] + ], + ] + declared_attr_reg: Dict[declared_attr[Any], Any] + + @classmethod + def setup_mapping( + cls, + registry: _RegistryType, + cls_: Type[_O], + dict_: _ClassDict, + table: Optional[FromClause], + mapper_kw: _MapperKwArgs, + ) -> Optional[_MapperConfig]: + manager = attributes.opt_manager_of_class(cls) + if manager and manager.class_ is cls_: + raise exc.InvalidRequestError( + f"Class {cls!r} already has been instrumented declaratively" + ) + + if cls_.__dict__.get("__abstract__", False): + return None + + defer_map = _get_immediate_cls_attr( + cls_, "_sa_decl_prepare_nocascade", strict=True + ) or hasattr(cls_, "_sa_decl_prepare") + + if defer_map: + return _DeferredMapperConfig( + registry, cls_, dict_, table, mapper_kw + ) + else: + return _ClassScanMapperConfig( + registry, cls_, dict_, table, mapper_kw + ) + + def __init__( + self, + registry: _RegistryType, + cls_: Type[Any], + mapper_kw: _MapperKwArgs, + ): + self.cls = util.assert_arg_type(cls_, type, "cls_") + self.classname = cls_.__name__ + self.properties = util.OrderedDict() + self.declared_attr_reg = {} + + if not mapper_kw.get("non_primary", False): + instrumentation.register_class( + self.cls, + finalize=False, + registry=registry, + declarative_scan=self, + init_method=registry.constructor, + ) + else: + manager = attributes.opt_manager_of_class(self.cls) + if not manager or not manager.is_mapped: + raise exc.InvalidRequestError( + "Class %s has no primary mapper configured. Configure " + "a primary mapper first before setting up a non primary " + "Mapper." % self.cls + ) + + def set_cls_attribute(self, attrname: str, value: _T) -> _T: + manager = instrumentation.manager_of_class(self.cls) + manager.install_member(attrname, value) + return value + + def map(self, mapper_kw: _MapperKwArgs = ...) -> Mapper[Any]: + raise NotImplementedError() + + def _early_mapping(self, mapper_kw: _MapperKwArgs) -> None: + self.map(mapper_kw) + + +class _ImperativeMapperConfig(_MapperConfig): + __slots__ = ("local_table", "inherits") + + def __init__( + self, + registry: _RegistryType, + cls_: Type[_O], + table: Optional[FromClause], + mapper_kw: _MapperKwArgs, + ): + super().__init__(registry, cls_, mapper_kw) + + self.local_table = self.set_cls_attribute("__table__", table) + + with mapperlib._CONFIGURE_MUTEX: + if not mapper_kw.get("non_primary", False): + clsregistry.add_class( + self.classname, self.cls, registry._class_registry + ) + + self._setup_inheritance(mapper_kw) + + self._early_mapping(mapper_kw) + + def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]: + mapper_cls = Mapper + + return self.set_cls_attribute( + "__mapper__", + mapper_cls(self.cls, self.local_table, **mapper_kw), + ) + + def _setup_inheritance(self, mapper_kw: _MapperKwArgs) -> None: + cls = self.cls + + inherits = mapper_kw.get("inherits", None) + + if inherits is None: + # since we search for classical mappings now, search for + # multiple mapped bases as well and raise an error. + inherits_search = [] + for base_ in cls.__bases__: + c = _resolve_for_abstract_or_classical(base_) + if c is None: + continue + + if _is_supercls_for_inherits(c) and c not in inherits_search: + inherits_search.append(c) + + if inherits_search: + if len(inherits_search) > 1: + raise exc.InvalidRequestError( + "Class %s has multiple mapped bases: %r" + % (cls, inherits_search) + ) + inherits = inherits_search[0] + elif isinstance(inherits, Mapper): + inherits = inherits.class_ + + self.inherits = inherits + + +class _CollectedAnnotation(NamedTuple): + raw_annotation: _AnnotationScanType + mapped_container: Optional[Type[Mapped[Any]]] + extracted_mapped_annotation: Union[_AnnotationScanType, str] + is_dataclass: bool + attr_value: Any + originating_module: str + originating_class: Type[Any] + + +class _ClassScanMapperConfig(_MapperConfig): + __slots__ = ( + "registry", + "clsdict_view", + "collected_attributes", + "collected_annotations", + "local_table", + "persist_selectable", + "declared_columns", + "column_ordering", + "column_copies", + "table_args", + "tablename", + "mapper_args", + "mapper_args_fn", + "table_fn", + "inherits", + "single", + "allow_dataclass_fields", + "dataclass_setup_arguments", + "is_dataclass_prior_to_mapping", + "allow_unmapped_annotations", + ) + + is_deferred = False + registry: _RegistryType + clsdict_view: _ClassDict + collected_annotations: Dict[str, _CollectedAnnotation] + collected_attributes: Dict[str, Any] + local_table: Optional[FromClause] + persist_selectable: Optional[FromClause] + declared_columns: util.OrderedSet[Column[Any]] + column_ordering: Dict[Column[Any], int] + column_copies: Dict[ + Union[MappedColumn[Any], Column[Any]], + Union[MappedColumn[Any], Column[Any]], + ] + tablename: Optional[str] + mapper_args: Mapping[str, Any] + table_args: Optional[_TableArgsType] + mapper_args_fn: Optional[Callable[[], Dict[str, Any]]] + inherits: Optional[Type[Any]] + single: bool + + is_dataclass_prior_to_mapping: bool + allow_unmapped_annotations: bool + + dataclass_setup_arguments: Optional[_DataclassArguments] + """if the class has SQLAlchemy native dataclass parameters, where + we will turn the class into a dataclass within the declarative mapping + process. + + """ + + allow_dataclass_fields: bool + """if true, look for dataclass-processed Field objects on the target + class as well as superclasses and extract ORM mapping directives from + the "metadata" attribute of each Field. + + if False, dataclass fields can still be used, however they won't be + mapped. + + """ + + def __init__( + self, + registry: _RegistryType, + cls_: Type[_O], + dict_: _ClassDict, + table: Optional[FromClause], + mapper_kw: _MapperKwArgs, + ): + # grab class dict before the instrumentation manager has been added. + # reduces cycles + self.clsdict_view = ( + util.immutabledict(dict_) if dict_ else util.EMPTY_DICT + ) + super().__init__(registry, cls_, mapper_kw) + self.registry = registry + self.persist_selectable = None + + self.collected_attributes = {} + self.collected_annotations = {} + self.declared_columns = util.OrderedSet() + self.column_ordering = {} + self.column_copies = {} + self.single = False + self.dataclass_setup_arguments = dca = getattr( + self.cls, "_sa_apply_dc_transforms", None + ) + + self.allow_unmapped_annotations = getattr( + self.cls, "__allow_unmapped__", False + ) or bool(self.dataclass_setup_arguments) + + self.is_dataclass_prior_to_mapping = cld = dataclasses.is_dataclass( + cls_ + ) + + sdk = _get_immediate_cls_attr(cls_, "__sa_dataclass_metadata_key__") + + # we don't want to consume Field objects from a not-already-dataclass. + # the Field objects won't have their "name" or "type" populated, + # and while it seems like we could just set these on Field as we + # read them, Field is documented as "user read only" and we need to + # stay far away from any off-label use of dataclasses APIs. + if (not cld or dca) and sdk: + raise exc.InvalidRequestError( + "SQLAlchemy mapped dataclasses can't consume mapping " + "information from dataclass.Field() objects if the immediate " + "class is not already a dataclass." + ) + + # if already a dataclass, and __sa_dataclass_metadata_key__ present, + # then also look inside of dataclass.Field() objects yielded by + # dataclasses.get_fields(cls) when scanning for attributes + self.allow_dataclass_fields = bool(sdk and cld) + + self._setup_declared_events() + + self._scan_attributes() + + self._setup_dataclasses_transforms() + + with mapperlib._CONFIGURE_MUTEX: + clsregistry.add_class( + self.classname, self.cls, registry._class_registry + ) + + self._setup_inheriting_mapper(mapper_kw) + + self._extract_mappable_attributes() + + self._extract_declared_columns() + + self._setup_table(table) + + self._setup_inheriting_columns(mapper_kw) + + self._early_mapping(mapper_kw) + + def _setup_declared_events(self) -> None: + if _get_immediate_cls_attr(self.cls, "__declare_last__"): + + @event.listens_for(Mapper, "after_configured") + def after_configured() -> None: + cast( + "_DeclMappedClassProtocol[Any]", self.cls + ).__declare_last__() + + if _get_immediate_cls_attr(self.cls, "__declare_first__"): + + @event.listens_for(Mapper, "before_configured") + def before_configured() -> None: + cast( + "_DeclMappedClassProtocol[Any]", self.cls + ).__declare_first__() + + def _cls_attr_override_checker( + self, cls: Type[_O] + ) -> Callable[[str, Any], bool]: + """Produce a function that checks if a class has overridden an + attribute, taking SQLAlchemy-enabled dataclass fields into account. + + """ + + if self.allow_dataclass_fields: + sa_dataclass_metadata_key = _get_immediate_cls_attr( + cls, "__sa_dataclass_metadata_key__" + ) + else: + sa_dataclass_metadata_key = None + + if not sa_dataclass_metadata_key: + + def attribute_is_overridden(key: str, obj: Any) -> bool: + return getattr(cls, key, obj) is not obj + + else: + all_datacls_fields = { + f.name: f.metadata[sa_dataclass_metadata_key] + for f in util.dataclass_fields(cls) + if sa_dataclass_metadata_key in f.metadata + } + local_datacls_fields = { + f.name: f.metadata[sa_dataclass_metadata_key] + for f in util.local_dataclass_fields(cls) + if sa_dataclass_metadata_key in f.metadata + } + + absent = object() + + def attribute_is_overridden(key: str, obj: Any) -> bool: + if _is_declarative_props(obj): + obj = obj.fget + + # this function likely has some failure modes still if + # someone is doing a deep mixing of the same attribute + # name as plain Python attribute vs. dataclass field. + + ret = local_datacls_fields.get(key, absent) + if _is_declarative_props(ret): + ret = ret.fget + + if ret is obj: + return False + elif ret is not absent: + return True + + all_field = all_datacls_fields.get(key, absent) + + ret = getattr(cls, key, obj) + + if ret is obj: + return False + + # for dataclasses, this could be the + # 'default' of the field. so filter more specifically + # for an already-mapped InstrumentedAttribute + if ret is not absent and isinstance( + ret, InstrumentedAttribute + ): + return True + + if all_field is obj: + return False + elif all_field is not absent: + return True + + # can't find another attribute + return False + + return attribute_is_overridden + + _include_dunders = { + "__table__", + "__mapper_args__", + "__tablename__", + "__table_args__", + } + + _match_exclude_dunders = re.compile(r"^(?:_sa_|__)") + + def _cls_attr_resolver( + self, cls: Type[Any] + ) -> Callable[[], Iterable[Tuple[str, Any, Any, bool]]]: + """produce a function to iterate the "attributes" of a class + which we want to consider for mapping, adjusting for SQLAlchemy fields + embedded in dataclass fields. + + """ + cls_annotations = util.get_annotations(cls) + + cls_vars = vars(cls) + + _include_dunders = self._include_dunders + _match_exclude_dunders = self._match_exclude_dunders + + names = [ + n + for n in util.merge_lists_w_ordering( + list(cls_vars), list(cls_annotations) + ) + if not _match_exclude_dunders.match(n) or n in _include_dunders + ] + + if self.allow_dataclass_fields: + sa_dataclass_metadata_key: Optional[str] = _get_immediate_cls_attr( + cls, "__sa_dataclass_metadata_key__" + ) + else: + sa_dataclass_metadata_key = None + + if not sa_dataclass_metadata_key: + + def local_attributes_for_class() -> ( + Iterable[Tuple[str, Any, Any, bool]] + ): + return ( + ( + name, + cls_vars.get(name), + cls_annotations.get(name), + False, + ) + for name in names + ) + + else: + dataclass_fields = { + field.name: field for field in util.local_dataclass_fields(cls) + } + + fixed_sa_dataclass_metadata_key = sa_dataclass_metadata_key + + def local_attributes_for_class() -> ( + Iterable[Tuple[str, Any, Any, bool]] + ): + for name in names: + field = dataclass_fields.get(name, None) + if field and sa_dataclass_metadata_key in field.metadata: + yield field.name, _as_dc_declaredattr( + field.metadata, fixed_sa_dataclass_metadata_key + ), cls_annotations.get(field.name), True + else: + yield name, cls_vars.get(name), cls_annotations.get( + name + ), False + + return local_attributes_for_class + + def _scan_attributes(self) -> None: + cls = self.cls + + cls_as_Decl = cast("_DeclMappedClassProtocol[Any]", cls) + + clsdict_view = self.clsdict_view + collected_attributes = self.collected_attributes + column_copies = self.column_copies + _include_dunders = self._include_dunders + mapper_args_fn = None + table_args = inherited_table_args = None + table_fn = None + tablename = None + fixed_table = "__table__" in clsdict_view + + attribute_is_overridden = self._cls_attr_override_checker(self.cls) + + bases = [] + + for base in cls.__mro__: + # collect bases and make sure standalone columns are copied + # to be the column they will ultimately be on the class, + # so that declared_attr functions use the right columns. + # need to do this all the way up the hierarchy first + # (see #8190) + + class_mapped = base is not cls and _is_supercls_for_inherits(base) + + local_attributes_for_class = self._cls_attr_resolver(base) + + if not class_mapped and base is not cls: + locally_collected_columns = self._produce_column_copies( + local_attributes_for_class, + attribute_is_overridden, + fixed_table, + base, + ) + else: + locally_collected_columns = {} + + bases.append( + ( + base, + class_mapped, + local_attributes_for_class, + locally_collected_columns, + ) + ) + + for ( + base, + class_mapped, + local_attributes_for_class, + locally_collected_columns, + ) in bases: + # this transfer can also take place as we scan each name + # for finer-grained control of how collected_attributes is + # populated, as this is what impacts column ordering. + # however it's simpler to get it out of the way here. + collected_attributes.update(locally_collected_columns) + + for ( + name, + obj, + annotation, + is_dataclass_field, + ) in local_attributes_for_class(): + if name in _include_dunders: + if name == "__mapper_args__": + check_decl = _check_declared_props_nocascade( + obj, name, cls + ) + if not mapper_args_fn and ( + not class_mapped or check_decl + ): + # don't even invoke __mapper_args__ until + # after we've determined everything about the + # mapped table. + # make a copy of it so a class-level dictionary + # is not overwritten when we update column-based + # arguments. + def _mapper_args_fn() -> Dict[str, Any]: + return dict(cls_as_Decl.__mapper_args__) + + mapper_args_fn = _mapper_args_fn + + elif name == "__tablename__": + check_decl = _check_declared_props_nocascade( + obj, name, cls + ) + if not tablename and (not class_mapped or check_decl): + tablename = cls_as_Decl.__tablename__ + elif name == "__table__": + check_decl = _check_declared_props_nocascade( + obj, name, cls + ) + # if a @declared_attr using "__table__" is detected, + # wrap up a callable to look for "__table__" from + # the final concrete class when we set up a table. + # this was fixed by + # #11509, regression in 2.0 from version 1.4. + if check_decl and not table_fn: + # don't even invoke __table__ until we're ready + def _table_fn() -> FromClause: + return cls_as_Decl.__table__ + + table_fn = _table_fn + + elif name == "__table_args__": + check_decl = _check_declared_props_nocascade( + obj, name, cls + ) + if not table_args and (not class_mapped or check_decl): + table_args = cls_as_Decl.__table_args__ + if not isinstance( + table_args, (tuple, dict, type(None)) + ): + raise exc.ArgumentError( + "__table_args__ value must be a tuple, " + "dict, or None" + ) + if base is not cls: + inherited_table_args = True + else: + # any other dunder names; should not be here + # as we have tested for all four names in + # _include_dunders + assert False + elif class_mapped: + if _is_declarative_props(obj) and not obj._quiet: + util.warn( + "Regular (i.e. not __special__) " + "attribute '%s.%s' uses @declared_attr, " + "but owning class %s is mapped - " + "not applying to subclass %s." + % (base.__name__, name, base, cls) + ) + + continue + elif base is not cls: + # we're a mixin, abstract base, or something that is + # acting like that for now. + + if isinstance(obj, (Column, MappedColumn)): + # already copied columns to the mapped class. + continue + elif isinstance(obj, MapperProperty): + raise exc.InvalidRequestError( + "Mapper properties (i.e. deferred," + "column_property(), relationship(), etc.) must " + "be declared as @declared_attr callables " + "on declarative mixin classes. For dataclass " + "field() objects, use a lambda:" + ) + elif _is_declarative_props(obj): + # tried to get overloads to tell this to + # pylance, no luck + assert obj is not None + + if obj._cascading: + if name in clsdict_view: + # unfortunately, while we can use the user- + # defined attribute here to allow a clean + # override, if there's another + # subclass below then it still tries to use + # this. not sure if there is enough + # information here to add this as a feature + # later on. + util.warn( + "Attribute '%s' on class %s cannot be " + "processed due to " + "@declared_attr.cascading; " + "skipping" % (name, cls) + ) + collected_attributes[name] = column_copies[obj] = ( + ret + ) = obj.__get__(obj, cls) + setattr(cls, name, ret) + else: + if is_dataclass_field: + # access attribute using normal class access + # first, to see if it's been mapped on a + # superclass. note if the dataclasses.field() + # has "default", this value can be anything. + ret = getattr(cls, name, None) + + # so, if it's anything that's not ORM + # mapped, assume we should invoke the + # declared_attr + if not isinstance(ret, InspectionAttr): + ret = obj.fget() + else: + # access attribute using normal class access. + # if the declared attr already took place + # on a superclass that is mapped, then + # this is no longer a declared_attr, it will + # be the InstrumentedAttribute + ret = getattr(cls, name) + + # correct for proxies created from hybrid_property + # or similar. note there is no known case that + # produces nested proxies, so we are only + # looking one level deep right now. + + if ( + isinstance(ret, InspectionAttr) + and attr_is_internal_proxy(ret) + and not isinstance( + ret.original_property, MapperProperty + ) + ): + ret = ret.descriptor + + collected_attributes[name] = column_copies[obj] = ( + ret + ) + + if ( + isinstance(ret, (Column, MapperProperty)) + and ret.doc is None + ): + ret.doc = obj.__doc__ + + self._collect_annotation( + name, + obj._collect_return_annotation(), + base, + True, + obj, + ) + elif _is_mapped_annotation(annotation, cls, base): + # Mapped annotation without any object. + # product_column_copies should have handled this. + # if future support for other MapperProperty, + # then test if this name is already handled and + # otherwise proceed to generate. + if not fixed_table: + assert ( + name in collected_attributes + or attribute_is_overridden(name, None) + ) + continue + else: + # here, the attribute is some other kind of + # property that we assume is not part of the + # declarative mapping. however, check for some + # more common mistakes + self._warn_for_decl_attributes(base, name, obj) + elif is_dataclass_field and ( + name not in clsdict_view or clsdict_view[name] is not obj + ): + # here, we are definitely looking at the target class + # and not a superclass. this is currently a + # dataclass-only path. if the name is only + # a dataclass field and isn't in local cls.__dict__, + # put the object there. + # assert that the dataclass-enabled resolver agrees + # with what we are seeing + + assert not attribute_is_overridden(name, obj) + + if _is_declarative_props(obj): + obj = obj.fget() + + collected_attributes[name] = obj + self._collect_annotation( + name, annotation, base, False, obj + ) + else: + collected_annotation = self._collect_annotation( + name, annotation, base, None, obj + ) + is_mapped = ( + collected_annotation is not None + and collected_annotation.mapped_container is not None + ) + generated_obj = ( + collected_annotation.attr_value + if collected_annotation is not None + else obj + ) + if obj is None and not fixed_table and is_mapped: + collected_attributes[name] = ( + generated_obj + if generated_obj is not None + else MappedColumn() + ) + elif name in clsdict_view: + collected_attributes[name] = obj + # else if the name is not in the cls.__dict__, + # don't collect it as an attribute. + # we will see the annotation only, which is meaningful + # both for mapping and dataclasses setup + + if inherited_table_args and not tablename: + table_args = None + + self.table_args = table_args + self.tablename = tablename + self.mapper_args_fn = mapper_args_fn + self.table_fn = table_fn + + def _setup_dataclasses_transforms(self) -> None: + dataclass_setup_arguments = self.dataclass_setup_arguments + if not dataclass_setup_arguments: + return + + # can't use is_dataclass since it uses hasattr + if "__dataclass_fields__" in self.cls.__dict__: + raise exc.InvalidRequestError( + f"Class {self.cls} is already a dataclass; ensure that " + "base classes / decorator styles of establishing dataclasses " + "are not being mixed. " + "This can happen if a class that inherits from " + "'MappedAsDataclass', even indirectly, is been mapped with " + "'@registry.mapped_as_dataclass'" + ) + + # can't create a dataclass if __table__ is already there. This would + # fail an assertion when calling _get_arguments_for_make_dataclass: + # assert False, "Mapped[] received without a mapping declaration" + if "__table__" in self.cls.__dict__: + raise exc.InvalidRequestError( + f"Class {self.cls} already defines a '__table__'. " + "ORM Annotated Dataclasses do not support a pre-existing " + "'__table__' element" + ) + + warn_for_non_dc_attrs = collections.defaultdict(list) + + def _allow_dataclass_field( + key: str, originating_class: Type[Any] + ) -> bool: + if ( + originating_class is not self.cls + and "__dataclass_fields__" not in originating_class.__dict__ + ): + warn_for_non_dc_attrs[originating_class].append(key) + + return True + + manager = instrumentation.manager_of_class(self.cls) + assert manager is not None + + field_list = [ + _AttributeOptions._get_arguments_for_make_dataclass( + key, + anno, + mapped_container, + self.collected_attributes.get(key, _NoArg.NO_ARG), + ) + for key, anno, mapped_container in ( + ( + key, + mapped_anno if mapped_anno else raw_anno, + mapped_container, + ) + for key, ( + raw_anno, + mapped_container, + mapped_anno, + is_dc, + attr_value, + originating_module, + originating_class, + ) in self.collected_annotations.items() + if _allow_dataclass_field(key, originating_class) + and ( + key not in self.collected_attributes + # issue #9226; check for attributes that we've collected + # which are already instrumented, which we would assume + # mean we are in an ORM inheritance mapping and this + # attribute is already mapped on the superclass. Under + # no circumstance should any QueryableAttribute be sent to + # the dataclass() function; anything that's mapped should + # be Field and that's it + or not isinstance( + self.collected_attributes[key], QueryableAttribute + ) + ) + ) + ] + + if warn_for_non_dc_attrs: + for ( + originating_class, + non_dc_attrs, + ) in warn_for_non_dc_attrs.items(): + util.warn_deprecated( + f"When transforming {self.cls} to a dataclass, " + f"attribute(s) " + f"{', '.join(repr(key) for key in non_dc_attrs)} " + f"originates from superclass " + f"{originating_class}, which is not a dataclass. This " + f"usage is deprecated and will raise an error in " + f"SQLAlchemy 2.1. When declaring SQLAlchemy Declarative " + f"Dataclasses, ensure that all mixin classes and other " + f"superclasses which include attributes are also a " + f"subclass of MappedAsDataclass.", + "2.0", + code="dcmx", + ) + + annotations = {} + defaults = {} + for item in field_list: + if len(item) == 2: + name, tp = item + elif len(item) == 3: + name, tp, spec = item + defaults[name] = spec + else: + assert False + annotations[name] = tp + + for k, v in defaults.items(): + setattr(self.cls, k, v) + + self._apply_dataclasses_to_any_class( + dataclass_setup_arguments, self.cls, annotations + ) + + @classmethod + def _update_annotations_for_non_mapped_class( + cls, klass: Type[_O] + ) -> Mapping[str, _AnnotationScanType]: + cls_annotations = util.get_annotations(klass) + + new_anno = {} + for name, annotation in cls_annotations.items(): + if _is_mapped_annotation(annotation, klass, klass): + extracted = _extract_mapped_subtype( + annotation, + klass, + klass.__module__, + name, + type(None), + required=False, + is_dataclass_field=False, + expect_mapped=False, + ) + if extracted: + inner, _ = extracted + new_anno[name] = inner + else: + new_anno[name] = annotation + return new_anno + + @classmethod + def _apply_dataclasses_to_any_class( + cls, + dataclass_setup_arguments: _DataclassArguments, + klass: Type[_O], + use_annotations: Mapping[str, _AnnotationScanType], + ) -> None: + cls._assert_dc_arguments(dataclass_setup_arguments) + + dataclass_callable = dataclass_setup_arguments["dataclass_callable"] + if dataclass_callable is _NoArg.NO_ARG: + dataclass_callable = dataclasses.dataclass + + restored: Optional[Any] + + if use_annotations: + # apply constructed annotations that should look "normal" to a + # dataclasses callable, based on the fields present. This + # means remove the Mapped[] container and ensure all Field + # entries have an annotation + restored = util.get_annotations(klass) + klass.__annotations__ = cast("Dict[str, Any]", use_annotations) + else: + restored = None + + try: + dataclass_callable( # type: ignore[call-overload] + klass, + **{ # type: ignore[call-overload,unused-ignore] + k: v + for k, v in dataclass_setup_arguments.items() + if v is not _NoArg.NO_ARG and k != "dataclass_callable" + }, + ) + except (TypeError, ValueError) as ex: + raise exc.InvalidRequestError( + f"Python dataclasses error encountered when creating " + f"dataclass for {klass.__name__!r}: " + f"{ex!r}. Please refer to Python dataclasses " + "documentation for additional information.", + code="dcte", + ) from ex + finally: + # restore original annotations outside of the dataclasses + # process; for mixins and __abstract__ superclasses, SQLAlchemy + # Declarative will need to see the Mapped[] container inside the + # annotations in order to map subclasses + if use_annotations: + if restored is None: + del klass.__annotations__ + else: + klass.__annotations__ = restored # type: ignore[assignment] # noqa: E501 + + @classmethod + def _assert_dc_arguments(cls, arguments: _DataclassArguments) -> None: + allowed = { + "init", + "repr", + "order", + "eq", + "unsafe_hash", + "kw_only", + "match_args", + "dataclass_callable", + } + disallowed_args = set(arguments).difference(allowed) + if disallowed_args: + msg = ", ".join(f"{arg!r}" for arg in sorted(disallowed_args)) + raise exc.ArgumentError( + f"Dataclass argument(s) {msg} are not accepted" + ) + + def _collect_annotation( + self, + name: str, + raw_annotation: _AnnotationScanType, + originating_class: Type[Any], + expect_mapped: Optional[bool], + attr_value: Any, + ) -> Optional[_CollectedAnnotation]: + if name in self.collected_annotations: + return self.collected_annotations[name] + + if raw_annotation is None: + return None + + is_dataclass = self.is_dataclass_prior_to_mapping + allow_unmapped = self.allow_unmapped_annotations + + if expect_mapped is None: + is_dataclass_field = isinstance(attr_value, dataclasses.Field) + expect_mapped = ( + not is_dataclass_field + and not allow_unmapped + and ( + attr_value is None + or isinstance(attr_value, _MappedAttribute) + ) + ) + + is_dataclass_field = False + extracted = _extract_mapped_subtype( + raw_annotation, + self.cls, + originating_class.__module__, + name, + type(attr_value), + required=False, + is_dataclass_field=is_dataclass_field, + expect_mapped=expect_mapped and not is_dataclass, + ) + if extracted is None: + # ClassVar can come out here + return None + + extracted_mapped_annotation, mapped_container = extracted + + if attr_value is None and not is_literal(extracted_mapped_annotation): + for elem in get_args(extracted_mapped_annotation): + if is_fwd_ref( + elem, check_generic=True, check_for_plain_string=True + ): + elem = de_stringify_annotation( + self.cls, + elem, + originating_class.__module__, + include_generic=True, + ) + # look in Annotated[...] for an ORM construct, + # such as Annotated[int, mapped_column(primary_key=True)] + if isinstance(elem, _IntrospectsAnnotations): + attr_value = elem.found_in_pep593_annotated() + + self.collected_annotations[name] = ca = _CollectedAnnotation( + raw_annotation, + mapped_container, + extracted_mapped_annotation, + is_dataclass, + attr_value, + originating_class.__module__, + originating_class, + ) + return ca + + def _warn_for_decl_attributes( + self, cls: Type[Any], key: str, c: Any + ) -> None: + if isinstance(c, expression.ColumnElement): + util.warn( + f"Attribute '{key}' on class {cls} appears to " + "be a non-schema SQLAlchemy expression " + "object; this won't be part of the declarative mapping. " + "To map arbitrary expressions, use ``column_property()`` " + "or a similar function such as ``deferred()``, " + "``query_expression()`` etc. " + ) + + def _produce_column_copies( + self, + attributes_for_class: Callable[ + [], Iterable[Tuple[str, Any, Any, bool]] + ], + attribute_is_overridden: Callable[[str, Any], bool], + fixed_table: bool, + originating_class: Type[Any], + ) -> Dict[str, Union[Column[Any], MappedColumn[Any]]]: + cls = self.cls + dict_ = self.clsdict_view + locally_collected_attributes = {} + column_copies = self.column_copies + # copy mixin columns to the mapped class + + for name, obj, annotation, is_dataclass in attributes_for_class(): + if ( + not fixed_table + and obj is None + and _is_mapped_annotation(annotation, cls, originating_class) + ): + # obj is None means this is the annotation only path + + if attribute_is_overridden(name, obj): + # perform same "overridden" check as we do for + # Column/MappedColumn, this is how a mixin col is not + # applied to an inherited subclass that does not have + # the mixin. the anno-only path added here for + # #9564 + continue + + collected_annotation = self._collect_annotation( + name, annotation, originating_class, True, obj + ) + obj = ( + collected_annotation.attr_value + if collected_annotation is not None + else obj + ) + if obj is None: + obj = MappedColumn() + + locally_collected_attributes[name] = obj + setattr(cls, name, obj) + + elif isinstance(obj, (Column, MappedColumn)): + if attribute_is_overridden(name, obj): + # if column has been overridden + # (like by the InstrumentedAttribute of the + # superclass), skip. don't collect the annotation + # either (issue #8718) + continue + + collected_annotation = self._collect_annotation( + name, annotation, originating_class, True, obj + ) + obj = ( + collected_annotation.attr_value + if collected_annotation is not None + else obj + ) + + if name not in dict_ and not ( + "__table__" in dict_ + and (getattr(obj, "name", None) or name) + in dict_["__table__"].c + ): + if obj.foreign_keys: + for fk in obj.foreign_keys: + if ( + fk._table_column is not None + and fk._table_column.table is None + ): + raise exc.InvalidRequestError( + "Columns with foreign keys to " + "non-table-bound " + "columns must be declared as " + "@declared_attr callables " + "on declarative mixin classes. " + "For dataclass " + "field() objects, use a lambda:." + ) + + column_copies[obj] = copy_ = obj._copy() + + locally_collected_attributes[name] = copy_ + setattr(cls, name, copy_) + + return locally_collected_attributes + + def _extract_mappable_attributes(self) -> None: + cls = self.cls + collected_attributes = self.collected_attributes + + our_stuff = self.properties + + _include_dunders = self._include_dunders + + late_mapped = _get_immediate_cls_attr( + cls, "_sa_decl_prepare_nocascade", strict=True + ) + + allow_unmapped_annotations = self.allow_unmapped_annotations + expect_annotations_wo_mapped = ( + allow_unmapped_annotations or self.is_dataclass_prior_to_mapping + ) + + look_for_dataclass_things = bool(self.dataclass_setup_arguments) + + for k in list(collected_attributes): + if k in _include_dunders: + continue + + value = collected_attributes[k] + + if _is_declarative_props(value): + # @declared_attr in collected_attributes only occurs here for a + # @declared_attr that's directly on the mapped class; + # for a mixin, these have already been evaluated + if value._cascading: + util.warn( + "Use of @declared_attr.cascading only applies to " + "Declarative 'mixin' and 'abstract' classes. " + "Currently, this flag is ignored on mapped class " + "%s" % self.cls + ) + + value = getattr(cls, k) + + elif ( + isinstance(value, QueryableAttribute) + and value.class_ is not cls + and value.key != k + ): + # detect a QueryableAttribute that's already mapped being + # assigned elsewhere in userland, turn into a synonym() + value = SynonymProperty(value.key) + setattr(cls, k, value) + + if ( + isinstance(value, tuple) + and len(value) == 1 + and isinstance(value[0], (Column, _MappedAttribute)) + ): + util.warn( + "Ignoring declarative-like tuple value of attribute " + "'%s': possibly a copy-and-paste error with a comma " + "accidentally placed at the end of the line?" % k + ) + continue + elif look_for_dataclass_things and isinstance( + value, dataclasses.Field + ): + # we collected a dataclass Field; dataclasses would have + # set up the correct state on the class + continue + elif not isinstance(value, (Column, _DCAttributeOptions)): + # using @declared_attr for some object that + # isn't Column/MapperProperty/_DCAttributeOptions; remove + # from the clsdict_view + # and place the evaluated value onto the class. + collected_attributes.pop(k) + self._warn_for_decl_attributes(cls, k, value) + if not late_mapped: + setattr(cls, k, value) + continue + # we expect to see the name 'metadata' in some valid cases; + # however at this point we see it's assigned to something trying + # to be mapped, so raise for that. + # TODO: should "registry" here be also? might be too late + # to change that now (2.0 betas) + elif k in ("metadata",): + raise exc.InvalidRequestError( + f"Attribute name '{k}' is reserved when using the " + "Declarative API." + ) + elif isinstance(value, Column): + _undefer_column_name( + k, self.column_copies.get(value, value) # type: ignore + ) + else: + if isinstance(value, _IntrospectsAnnotations): + ( + annotation, + mapped_container, + extracted_mapped_annotation, + is_dataclass, + attr_value, + originating_module, + originating_class, + ) = self.collected_annotations.get( + k, (None, None, None, False, None, None, None) + ) + + # issue #8692 - don't do any annotation interpretation if + # an annotation were present and a container such as + # Mapped[] etc. were not used. If annotation is None, + # do declarative_scan so that the property can raise + # for required + if ( + mapped_container is not None + or annotation is None + # issue #10516: need to do declarative_scan even with + # a non-Mapped annotation if we are doing + # __allow_unmapped__, for things like col.name + # assignment + or allow_unmapped_annotations + ): + try: + value.declarative_scan( + self, + self.registry, + cls, + originating_module, + k, + mapped_container, + annotation, + extracted_mapped_annotation, + is_dataclass, + ) + except NameError as ne: + raise orm_exc.MappedAnnotationError( + f"Could not resolve all types within mapped " + f'annotation: "{annotation}". Ensure all ' + f"types are written correctly and are " + f"imported within the module in use." + ) from ne + else: + # assert that we were expecting annotations + # without Mapped[] were going to be passed. + # otherwise an error should have been raised + # by util._extract_mapped_subtype before we got here. + assert expect_annotations_wo_mapped + + if isinstance(value, _DCAttributeOptions): + if ( + value._has_dataclass_arguments + and not look_for_dataclass_things + ): + if isinstance(value, MapperProperty): + argnames = [ + "init", + "default_factory", + "repr", + "default", + "dataclass_metadata", + ] + else: + argnames = [ + "init", + "default_factory", + "repr", + "dataclass_metadata", + ] + + args = { + a + for a in argnames + if getattr( + value._attribute_options, f"dataclasses_{a}" + ) + is not _NoArg.NO_ARG + } + + raise exc.ArgumentError( + f"Attribute '{k}' on class {cls} includes " + f"dataclasses argument(s): " + f"{', '.join(sorted(repr(a) for a in args))} but " + f"class does not specify " + "SQLAlchemy native dataclass configuration." + ) + + if not isinstance(value, (MapperProperty, _MapsColumns)): + # filter for _DCAttributeOptions objects that aren't + # MapperProperty / mapped_column(). Currently this + # includes AssociationProxy. pop it from the things + # we're going to map and set it up as a descriptor + # on the class. + collected_attributes.pop(k) + + # Assoc Prox (or other descriptor object that may + # use _DCAttributeOptions) is usually here, except if + # 1. we're a + # dataclass, dataclasses would have removed the + # attr here or 2. assoc proxy is coming from a + # superclass, we want it to be direct here so it + # tracks state or 3. assoc prox comes from + # declared_attr, uncommon case + setattr(cls, k, value) + continue + + our_stuff[k] = value + + def _extract_declared_columns(self) -> None: + our_stuff = self.properties + + # extract columns from the class dict + declared_columns = self.declared_columns + column_ordering = self.column_ordering + name_to_prop_key = collections.defaultdict(set) + + for key, c in list(our_stuff.items()): + if isinstance(c, _MapsColumns): + mp_to_assign = c.mapper_property_to_assign + if mp_to_assign: + our_stuff[key] = mp_to_assign + else: + # if no mapper property to assign, this currently means + # this is a MappedColumn that will produce a Column for us + del our_stuff[key] + + for col, sort_order in c.columns_to_assign: + if not isinstance(c, CompositeProperty): + name_to_prop_key[col.name].add(key) + declared_columns.add(col) + + # we would assert this, however we want the below + # warning to take effect instead. See #9630 + # assert col not in column_ordering + + column_ordering[col] = sort_order + + # if this is a MappedColumn and the attribute key we + # have is not what the column has for its key, map the + # Column explicitly under the attribute key name. + # otherwise, Mapper will map it under the column key. + if mp_to_assign is None and key != col.key: + our_stuff[key] = col + elif isinstance(c, Column): + # undefer previously occurred here, and now occurs earlier. + # ensure every column we get here has been named + assert c.name is not None + name_to_prop_key[c.name].add(key) + declared_columns.add(c) + # if the column is the same name as the key, + # remove it from the explicit properties dict. + # the normal rules for assigning column-based properties + # will take over, including precedence of columns + # in multi-column ColumnProperties. + if key == c.key: + del our_stuff[key] + + for name, keys in name_to_prop_key.items(): + if len(keys) > 1: + util.warn( + "On class %r, Column object %r named " + "directly multiple times, " + "only one will be used: %s. " + "Consider using orm.synonym instead" + % (self.classname, name, (", ".join(sorted(keys)))) + ) + + def _setup_table(self, table: Optional[FromClause] = None) -> None: + cls = self.cls + cls_as_Decl = cast("MappedClassProtocol[Any]", cls) + + tablename = self.tablename + table_args = self.table_args + clsdict_view = self.clsdict_view + declared_columns = self.declared_columns + column_ordering = self.column_ordering + + manager = attributes.manager_of_class(cls) + + if ( + self.table_fn is None + and "__table__" not in clsdict_view + and table is None + ): + if hasattr(cls, "__table_cls__"): + table_cls = cast( + Type[Table], + util.unbound_method_to_callable(cls.__table_cls__), # type: ignore # noqa: E501 + ) + else: + table_cls = Table + + if tablename is not None: + args: Tuple[Any, ...] = () + table_kw: Dict[str, Any] = {} + + if table_args: + if isinstance(table_args, dict): + table_kw = table_args + elif isinstance(table_args, tuple): + if isinstance(table_args[-1], dict): + args, table_kw = table_args[0:-1], table_args[-1] + else: + args = table_args + + autoload_with = clsdict_view.get("__autoload_with__") + if autoload_with: + table_kw["autoload_with"] = autoload_with + + autoload = clsdict_view.get("__autoload__") + if autoload: + table_kw["autoload"] = True + + sorted_columns = sorted( + declared_columns, + key=lambda c: column_ordering.get(c, 0), + ) + table = self.set_cls_attribute( + "__table__", + table_cls( + tablename, + self._metadata_for_cls(manager), + *sorted_columns, + *args, + **table_kw, + ), + ) + else: + if table is None: + if self.table_fn: + table = self.set_cls_attribute( + "__table__", self.table_fn() + ) + else: + table = cls_as_Decl.__table__ + if declared_columns: + for c in declared_columns: + if not table.c.contains_column(c): + raise exc.ArgumentError( + "Can't add additional column %r when " + "specifying __table__" % c.key + ) + + self.local_table = table + + def _metadata_for_cls(self, manager: ClassManager[Any]) -> MetaData: + meta: Optional[MetaData] = getattr(self.cls, "metadata", None) + if meta is not None: + return meta + else: + return manager.registry.metadata + + def _setup_inheriting_mapper(self, mapper_kw: _MapperKwArgs) -> None: + cls = self.cls + + inherits = mapper_kw.get("inherits", None) + + if inherits is None: + # since we search for classical mappings now, search for + # multiple mapped bases as well and raise an error. + inherits_search = [] + for base_ in cls.__bases__: + c = _resolve_for_abstract_or_classical(base_) + if c is None: + continue + + if _is_supercls_for_inherits(c) and c not in inherits_search: + inherits_search.append(c) + + if inherits_search: + if len(inherits_search) > 1: + raise exc.InvalidRequestError( + "Class %s has multiple mapped bases: %r" + % (cls, inherits_search) + ) + inherits = inherits_search[0] + elif isinstance(inherits, Mapper): + inherits = inherits.class_ + + self.inherits = inherits + + clsdict_view = self.clsdict_view + if "__table__" not in clsdict_view and self.tablename is None: + self.single = True + + def _setup_inheriting_columns(self, mapper_kw: _MapperKwArgs) -> None: + table = self.local_table + cls = self.cls + table_args = self.table_args + declared_columns = self.declared_columns + + if ( + table is None + and self.inherits is None + and not _get_immediate_cls_attr(cls, "__no_table__") + ): + raise exc.InvalidRequestError( + "Class %r does not have a __table__ or __tablename__ " + "specified and does not inherit from an existing " + "table-mapped class." % cls + ) + elif self.inherits: + inherited_mapper_or_config = _declared_mapping_info(self.inherits) + assert inherited_mapper_or_config is not None + inherited_table = inherited_mapper_or_config.local_table + inherited_persist_selectable = ( + inherited_mapper_or_config.persist_selectable + ) + + if table is None: + # single table inheritance. + # ensure no table args + if table_args: + raise exc.ArgumentError( + "Can't place __table_args__ on an inherited class " + "with no table." + ) + + # add any columns declared here to the inherited table. + if declared_columns and not isinstance(inherited_table, Table): + raise exc.ArgumentError( + f"Can't declare columns on single-table-inherited " + f"subclass {self.cls}; superclass {self.inherits} " + "is not mapped to a Table" + ) + + for col in declared_columns: + assert inherited_table is not None + if col.name in inherited_table.c: + if inherited_table.c[col.name] is col: + continue + raise exc.ArgumentError( + f"Column '{col}' on class {cls.__name__} " + f"conflicts with existing column " + f"'{inherited_table.c[col.name]}'. If using " + f"Declarative, consider using the " + "use_existing_column parameter of mapped_column() " + "to resolve conflicts." + ) + if col.primary_key: + raise exc.ArgumentError( + "Can't place primary key columns on an inherited " + "class with no table." + ) + + if TYPE_CHECKING: + assert isinstance(inherited_table, Table) + + inherited_table.append_column(col) + if ( + inherited_persist_selectable is not None + and inherited_persist_selectable is not inherited_table + ): + inherited_persist_selectable._refresh_for_new_column( + col + ) + + def _prepare_mapper_arguments(self, mapper_kw: _MapperKwArgs) -> None: + properties = self.properties + + if self.mapper_args_fn: + mapper_args = self.mapper_args_fn() + else: + mapper_args = {} + + if mapper_kw: + mapper_args.update(mapper_kw) + + if "properties" in mapper_args: + properties = dict(properties) + properties.update(mapper_args["properties"]) + + # make sure that column copies are used rather + # than the original columns from any mixins + for k in ("version_id_col", "polymorphic_on"): + if k in mapper_args: + v = mapper_args[k] + mapper_args[k] = self.column_copies.get(v, v) + + if "primary_key" in mapper_args: + mapper_args["primary_key"] = [ + self.column_copies.get(v, v) + for v in util.to_list(mapper_args["primary_key"]) + ] + + if "inherits" in mapper_args: + inherits_arg = mapper_args["inherits"] + if isinstance(inherits_arg, Mapper): + inherits_arg = inherits_arg.class_ + + if inherits_arg is not self.inherits: + raise exc.InvalidRequestError( + "mapper inherits argument given for non-inheriting " + "class %s" % (mapper_args["inherits"]) + ) + + if self.inherits: + mapper_args["inherits"] = self.inherits + + if self.inherits and not mapper_args.get("concrete", False): + # note the superclass is expected to have a Mapper assigned and + # not be a deferred config, as this is called within map() + inherited_mapper = class_mapper(self.inherits, False) + inherited_table = inherited_mapper.local_table + + # single or joined inheritance + # exclude any cols on the inherited table which are + # not mapped on the parent class, to avoid + # mapping columns specific to sibling/nephew classes + if "exclude_properties" not in mapper_args: + mapper_args["exclude_properties"] = exclude_properties = { + c.key + for c in inherited_table.c + if c not in inherited_mapper._columntoproperty + }.union(inherited_mapper.exclude_properties or ()) + exclude_properties.difference_update( + [c.key for c in self.declared_columns] + ) + + # look through columns in the current mapper that + # are keyed to a propname different than the colname + # (if names were the same, we'd have popped it out above, + # in which case the mapper makes this combination). + # See if the superclass has a similar column property. + # If so, join them together. + for k, col in list(properties.items()): + if not isinstance(col, expression.ColumnElement): + continue + if k in inherited_mapper._props: + p = inherited_mapper._props[k] + if isinstance(p, ColumnProperty): + # note here we place the subclass column + # first. See [ticket:1892] for background. + properties[k] = [col] + p.columns + result_mapper_args = mapper_args.copy() + result_mapper_args["properties"] = properties + self.mapper_args = result_mapper_args + + def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]: + self._prepare_mapper_arguments(mapper_kw) + if hasattr(self.cls, "__mapper_cls__"): + mapper_cls = cast( + "Type[Mapper[Any]]", + util.unbound_method_to_callable( + self.cls.__mapper_cls__ # type: ignore + ), + ) + else: + mapper_cls = Mapper + + return self.set_cls_attribute( + "__mapper__", + mapper_cls(self.cls, self.local_table, **self.mapper_args), + ) + + +@util.preload_module("sqlalchemy.orm.decl_api") +def _as_dc_declaredattr( + field_metadata: Mapping[str, Any], sa_dataclass_metadata_key: str +) -> Any: + # wrap lambdas inside dataclass fields inside an ad-hoc declared_attr. + # we can't write it because field.metadata is immutable :( so we have + # to go through extra trouble to compare these + decl_api = util.preloaded.orm_decl_api + obj = field_metadata[sa_dataclass_metadata_key] + if callable(obj) and not isinstance(obj, decl_api.declared_attr): + return decl_api.declared_attr(obj) + else: + return obj + + +class _DeferredMapperConfig(_ClassScanMapperConfig): + _cls: weakref.ref[Type[Any]] + + is_deferred = True + + _configs: util.OrderedDict[ + weakref.ref[Type[Any]], _DeferredMapperConfig + ] = util.OrderedDict() + + def _early_mapping(self, mapper_kw: _MapperKwArgs) -> None: + pass + + @property + def cls(self) -> Type[Any]: + return self._cls() # type: ignore + + @cls.setter + def cls(self, class_: Type[Any]) -> None: + self._cls = weakref.ref(class_, self._remove_config_cls) + self._configs[self._cls] = self + + @classmethod + def _remove_config_cls(cls, ref: weakref.ref[Type[Any]]) -> None: + cls._configs.pop(ref, None) + + @classmethod + def has_cls(cls, class_: Type[Any]) -> bool: + # 2.6 fails on weakref if class_ is an old style class + return isinstance(class_, type) and weakref.ref(class_) in cls._configs + + @classmethod + def raise_unmapped_for_cls(cls, class_: Type[Any]) -> NoReturn: + if hasattr(class_, "_sa_raise_deferred_config"): + class_._sa_raise_deferred_config() + + raise orm_exc.UnmappedClassError( + class_, + msg=( + f"Class {orm_exc._safe_cls_name(class_)} has a deferred " + "mapping on it. It is not yet usable as a mapped class." + ), + ) + + @classmethod + def config_for_cls(cls, class_: Type[Any]) -> _DeferredMapperConfig: + return cls._configs[weakref.ref(class_)] + + @classmethod + def classes_for_base( + cls, base_cls: Type[Any], sort: bool = True + ) -> List[_DeferredMapperConfig]: + classes_for_base = [ + m + for m, cls_ in [(m, m.cls) for m in cls._configs.values()] + if cls_ is not None and issubclass(cls_, base_cls) + ] + + if not sort: + return classes_for_base + + all_m_by_cls = {m.cls: m for m in classes_for_base} + + tuples: List[Tuple[_DeferredMapperConfig, _DeferredMapperConfig]] = [] + for m_cls in all_m_by_cls: + tuples.extend( + (all_m_by_cls[base_cls], all_m_by_cls[m_cls]) + for base_cls in m_cls.__bases__ + if base_cls in all_m_by_cls + ) + return list(topological.sort(tuples, classes_for_base)) + + def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]: + self._configs.pop(self._cls, None) + return super().map(mapper_kw) + + +def _add_attribute( + cls: Type[Any], key: str, value: MapperProperty[Any] +) -> None: + """add an attribute to an existing declarative class. + + This runs through the logic to determine MapperProperty, + adds it to the Mapper, adds a column to the mapped Table, etc. + + """ + + if "__mapper__" in cls.__dict__: + mapped_cls = cast("MappedClassProtocol[Any]", cls) + + def _table_or_raise(mc: MappedClassProtocol[Any]) -> Table: + if isinstance(mc.__table__, Table): + return mc.__table__ + raise exc.InvalidRequestError( + f"Cannot add a new attribute to mapped class {mc.__name__!r} " + "because it's not mapped against a table." + ) + + if isinstance(value, Column): + _undefer_column_name(key, value) + _table_or_raise(mapped_cls).append_column( + value, replace_existing=True + ) + mapped_cls.__mapper__.add_property(key, value) + elif isinstance(value, _MapsColumns): + mp = value.mapper_property_to_assign + for col, _ in value.columns_to_assign: + _undefer_column_name(key, col) + _table_or_raise(mapped_cls).append_column( + col, replace_existing=True + ) + if not mp: + mapped_cls.__mapper__.add_property(key, col) + if mp: + mapped_cls.__mapper__.add_property(key, mp) + elif isinstance(value, MapperProperty): + mapped_cls.__mapper__.add_property(key, value) + elif isinstance(value, QueryableAttribute) and value.key != key: + # detect a QueryableAttribute that's already mapped being + # assigned elsewhere in userland, turn into a synonym() + value = SynonymProperty(value.key) + mapped_cls.__mapper__.add_property(key, value) + else: + type.__setattr__(cls, key, value) + mapped_cls.__mapper__._expire_memoizations() + else: + type.__setattr__(cls, key, value) + + +def _del_attribute(cls: Type[Any], key: str) -> None: + if ( + "__mapper__" in cls.__dict__ + and key in cls.__dict__ + and not cast( + "MappedClassProtocol[Any]", cls + ).__mapper__._dispose_called + ): + value = cls.__dict__[key] + if isinstance( + value, (Column, _MapsColumns, MapperProperty, QueryableAttribute) + ): + raise NotImplementedError( + "Can't un-map individual mapped attributes on a mapped class." + ) + else: + type.__delattr__(cls, key) + cast( + "MappedClassProtocol[Any]", cls + ).__mapper__._expire_memoizations() + else: + type.__delattr__(cls, key) + + +def _declarative_constructor(self: Any, **kwargs: Any) -> None: + """A simple constructor that allows initialization from kwargs. + + Sets attributes on the constructed instance using the names and + values in ``kwargs``. + + Only keys that are present as + attributes of the instance's class are allowed. These could be, + for example, any mapped columns or relationships. + """ + cls_ = type(self) + for k in kwargs: + if not hasattr(cls_, k): + raise TypeError( + "%r is an invalid keyword argument for %s" % (k, cls_.__name__) + ) + setattr(self, k, kwargs[k]) + + +_declarative_constructor.__name__ = "__init__" + + +def _undefer_column_name(key: str, column: Column[Any]) -> None: + if column.key is None: + column.key = key + if column.name is None: + column.name = key diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/dependency.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/dependency.py new file mode 100644 index 0000000000000000000000000000000000000000..806052d4d5b59ad5e0058e3577a78e0424b8c01e --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/dependency.py @@ -0,0 +1,1302 @@ +# orm/dependency.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + + +"""Relationship dependencies.""" + +from __future__ import annotations + +from . import attributes +from . import exc +from . import sync +from . import unitofwork +from . import util as mapperutil +from .interfaces import MANYTOMANY +from .interfaces import MANYTOONE +from .interfaces import ONETOMANY +from .. import exc as sa_exc +from .. import sql +from .. import util + + +class DependencyProcessor: + def __init__(self, prop): + self.prop = prop + self.cascade = prop.cascade + self.mapper = prop.mapper + self.parent = prop.parent + self.secondary = prop.secondary + self.direction = prop.direction + self.post_update = prop.post_update + self.passive_deletes = prop.passive_deletes + self.passive_updates = prop.passive_updates + self.enable_typechecks = prop.enable_typechecks + if self.passive_deletes: + self._passive_delete_flag = attributes.PASSIVE_NO_INITIALIZE + else: + self._passive_delete_flag = attributes.PASSIVE_OFF + if self.passive_updates: + self._passive_update_flag = attributes.PASSIVE_NO_INITIALIZE + else: + self._passive_update_flag = attributes.PASSIVE_OFF + + self.sort_key = "%s_%s" % (self.parent._sort_key, prop.key) + self.key = prop.key + if not self.prop.synchronize_pairs: + raise sa_exc.ArgumentError( + "Can't build a DependencyProcessor for relationship %s. " + "No target attributes to populate between parent and " + "child are present" % self.prop + ) + + @classmethod + def from_relationship(cls, prop): + return _direction_to_processor[prop.direction](prop) + + def hasparent(self, state): + """return True if the given object instance has a parent, + according to the ``InstrumentedAttribute`` handled by this + ``DependencyProcessor``. + + """ + return self.parent.class_manager.get_impl(self.key).hasparent(state) + + def per_property_preprocessors(self, uow): + """establish actions and dependencies related to a flush. + + These actions will operate on all relevant states in + the aggregate. + + """ + uow.register_preprocessor(self, True) + + def per_property_flush_actions(self, uow): + after_save = unitofwork.ProcessAll(uow, self, False, True) + before_delete = unitofwork.ProcessAll(uow, self, True, True) + + parent_saves = unitofwork.SaveUpdateAll( + uow, self.parent.primary_base_mapper + ) + child_saves = unitofwork.SaveUpdateAll( + uow, self.mapper.primary_base_mapper + ) + + parent_deletes = unitofwork.DeleteAll( + uow, self.parent.primary_base_mapper + ) + child_deletes = unitofwork.DeleteAll( + uow, self.mapper.primary_base_mapper + ) + + self.per_property_dependencies( + uow, + parent_saves, + child_saves, + parent_deletes, + child_deletes, + after_save, + before_delete, + ) + + def per_state_flush_actions(self, uow, states, isdelete): + """establish actions and dependencies related to a flush. + + These actions will operate on all relevant states + individually. This occurs only if there are cycles + in the 'aggregated' version of events. + + """ + + child_base_mapper = self.mapper.primary_base_mapper + child_saves = unitofwork.SaveUpdateAll(uow, child_base_mapper) + child_deletes = unitofwork.DeleteAll(uow, child_base_mapper) + + # locate and disable the aggregate processors + # for this dependency + + if isdelete: + before_delete = unitofwork.ProcessAll(uow, self, True, True) + before_delete.disabled = True + else: + after_save = unitofwork.ProcessAll(uow, self, False, True) + after_save.disabled = True + + # check if the "child" side is part of the cycle + + if child_saves not in uow.cycles: + # based on the current dependencies we use, the saves/ + # deletes should always be in the 'cycles' collection + # together. if this changes, we will have to break up + # this method a bit more. + assert child_deletes not in uow.cycles + + # child side is not part of the cycle, so we will link per-state + # actions to the aggregate "saves", "deletes" actions + child_actions = [(child_saves, False), (child_deletes, True)] + child_in_cycles = False + else: + child_in_cycles = True + + # check if the "parent" side is part of the cycle + if not isdelete: + parent_saves = unitofwork.SaveUpdateAll( + uow, self.parent.base_mapper + ) + parent_deletes = before_delete = None + if parent_saves in uow.cycles: + parent_in_cycles = True + else: + parent_deletes = unitofwork.DeleteAll(uow, self.parent.base_mapper) + parent_saves = after_save = None + if parent_deletes in uow.cycles: + parent_in_cycles = True + + # now create actions /dependencies for each state. + + for state in states: + # detect if there's anything changed or loaded + # by a preprocessor on this state/attribute. In the + # case of deletes we may try to load missing items here as well. + sum_ = state.manager[self.key].impl.get_all_pending( + state, + state.dict, + ( + self._passive_delete_flag + if isdelete + else attributes.PASSIVE_NO_INITIALIZE + ), + ) + + if not sum_: + continue + + if isdelete: + before_delete = unitofwork.ProcessState(uow, self, True, state) + if parent_in_cycles: + parent_deletes = unitofwork.DeleteState(uow, state) + else: + after_save = unitofwork.ProcessState(uow, self, False, state) + if parent_in_cycles: + parent_saves = unitofwork.SaveUpdateState(uow, state) + + if child_in_cycles: + child_actions = [] + for child_state, child in sum_: + if child_state not in uow.states: + child_action = (None, None) + else: + (deleted, listonly) = uow.states[child_state] + if deleted: + child_action = ( + unitofwork.DeleteState(uow, child_state), + True, + ) + else: + child_action = ( + unitofwork.SaveUpdateState(uow, child_state), + False, + ) + child_actions.append(child_action) + + # establish dependencies between our possibly per-state + # parent action and our possibly per-state child action. + for child_action, childisdelete in child_actions: + self.per_state_dependencies( + uow, + parent_saves, + parent_deletes, + child_action, + after_save, + before_delete, + isdelete, + childisdelete, + ) + + def presort_deletes(self, uowcommit, states): + return False + + def presort_saves(self, uowcommit, states): + return False + + def process_deletes(self, uowcommit, states): + pass + + def process_saves(self, uowcommit, states): + pass + + def prop_has_changes(self, uowcommit, states, isdelete): + if not isdelete or self.passive_deletes: + passive = ( + attributes.PASSIVE_NO_INITIALIZE + | attributes.INCLUDE_PENDING_MUTATIONS + ) + elif self.direction is MANYTOONE: + # here, we were hoping to optimize having to fetch many-to-one + # for history and ignore it, if there's no further cascades + # to take place. however there are too many less common conditions + # that still take place and tests in test_relationships / + # test_cascade etc. will still fail. + passive = attributes.PASSIVE_NO_FETCH_RELATED + else: + passive = ( + attributes.PASSIVE_OFF | attributes.INCLUDE_PENDING_MUTATIONS + ) + + for s in states: + # TODO: add a high speed method + # to InstanceState which returns: attribute + # has a non-None value, or had one + history = uowcommit.get_attribute_history(s, self.key, passive) + if history and not history.empty(): + return True + else: + return ( + states + and not self.prop._is_self_referential + and self.mapper in uowcommit.mappers + ) + + def _verify_canload(self, state): + if self.prop.uselist and state is None: + raise exc.FlushError( + "Can't flush None value found in " + "collection %s" % (self.prop,) + ) + elif state is not None and not self.mapper._canload( + state, allow_subtypes=not self.enable_typechecks + ): + if self.mapper._canload(state, allow_subtypes=True): + raise exc.FlushError( + "Attempting to flush an item of type " + "%(x)s as a member of collection " + '"%(y)s". Expected an object of type ' + "%(z)s or a polymorphic subclass of " + "this type. If %(x)s is a subclass of " + '%(z)s, configure mapper "%(zm)s" to ' + "load this subtype polymorphically, or " + "set enable_typechecks=False to allow " + "any subtype to be accepted for flush. " + % { + "x": state.class_, + "y": self.prop, + "z": self.mapper.class_, + "zm": self.mapper, + } + ) + else: + raise exc.FlushError( + "Attempting to flush an item of type " + "%(x)s as a member of collection " + '"%(y)s". Expected an object of type ' + "%(z)s or a polymorphic subclass of " + "this type." + % { + "x": state.class_, + "y": self.prop, + "z": self.mapper.class_, + } + ) + + def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): + raise NotImplementedError() + + def _get_reversed_processed_set(self, uow): + if not self.prop._reverse_property: + return None + + process_key = tuple( + sorted([self.key] + [p.key for p in self.prop._reverse_property]) + ) + return uow.memo(("reverse_key", process_key), set) + + def _post_update(self, state, uowcommit, related, is_m2o_delete=False): + for x in related: + if not is_m2o_delete or x is not None: + uowcommit.register_post_update( + state, [r for l, r in self.prop.synchronize_pairs] + ) + break + + def _pks_changed(self, uowcommit, state): + raise NotImplementedError() + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, self.prop) + + +class OneToManyDP(DependencyProcessor): + def per_property_dependencies( + self, + uow, + parent_saves, + child_saves, + parent_deletes, + child_deletes, + after_save, + before_delete, + ): + if self.post_update: + child_post_updates = unitofwork.PostUpdateAll( + uow, self.mapper.primary_base_mapper, False + ) + child_pre_updates = unitofwork.PostUpdateAll( + uow, self.mapper.primary_base_mapper, True + ) + + uow.dependencies.update( + [ + (child_saves, after_save), + (parent_saves, after_save), + (after_save, child_post_updates), + (before_delete, child_pre_updates), + (child_pre_updates, parent_deletes), + (child_pre_updates, child_deletes), + ] + ) + else: + uow.dependencies.update( + [ + (parent_saves, after_save), + (after_save, child_saves), + (after_save, child_deletes), + (child_saves, parent_deletes), + (child_deletes, parent_deletes), + (before_delete, child_saves), + (before_delete, child_deletes), + ] + ) + + def per_state_dependencies( + self, + uow, + save_parent, + delete_parent, + child_action, + after_save, + before_delete, + isdelete, + childisdelete, + ): + if self.post_update: + child_post_updates = unitofwork.PostUpdateAll( + uow, self.mapper.primary_base_mapper, False + ) + child_pre_updates = unitofwork.PostUpdateAll( + uow, self.mapper.primary_base_mapper, True + ) + + # TODO: this whole block is not covered + # by any tests + if not isdelete: + if childisdelete: + uow.dependencies.update( + [ + (child_action, after_save), + (after_save, child_post_updates), + ] + ) + else: + uow.dependencies.update( + [ + (save_parent, after_save), + (child_action, after_save), + (after_save, child_post_updates), + ] + ) + else: + if childisdelete: + uow.dependencies.update( + [ + (before_delete, child_pre_updates), + (child_pre_updates, delete_parent), + ] + ) + else: + uow.dependencies.update( + [ + (before_delete, child_pre_updates), + (child_pre_updates, delete_parent), + ] + ) + elif not isdelete: + uow.dependencies.update( + [ + (save_parent, after_save), + (after_save, child_action), + (save_parent, child_action), + ] + ) + else: + uow.dependencies.update( + [(before_delete, child_action), (child_action, delete_parent)] + ) + + def presort_deletes(self, uowcommit, states): + # head object is being deleted, and we manage its list of + # child objects the child objects have to have their + # foreign key to the parent set to NULL + should_null_fks = ( + not self.cascade.delete and not self.passive_deletes == "all" + ) + + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + for child in history.deleted: + if child is not None and self.hasparent(child) is False: + if self.cascade.delete_orphan: + uowcommit.register_object(child, isdelete=True) + else: + uowcommit.register_object(child) + + if should_null_fks: + for child in history.unchanged: + if child is not None: + uowcommit.register_object( + child, operation="delete", prop=self.prop + ) + + def presort_saves(self, uowcommit, states): + children_added = uowcommit.memo(("children_added", self), set) + + should_null_fks = ( + not self.cascade.delete_orphan + and not self.passive_deletes == "all" + ) + + for state in states: + pks_changed = self._pks_changed(uowcommit, state) + + if not pks_changed or self.passive_updates: + passive = ( + attributes.PASSIVE_NO_INITIALIZE + | attributes.INCLUDE_PENDING_MUTATIONS + ) + else: + passive = ( + attributes.PASSIVE_OFF + | attributes.INCLUDE_PENDING_MUTATIONS + ) + + history = uowcommit.get_attribute_history(state, self.key, passive) + if history: + for child in history.added: + if child is not None: + uowcommit.register_object( + child, + cancel_delete=True, + operation="add", + prop=self.prop, + ) + + children_added.update(history.added) + + for child in history.deleted: + if not self.cascade.delete_orphan: + if should_null_fks: + uowcommit.register_object( + child, + isdelete=False, + operation="delete", + prop=self.prop, + ) + elif self.hasparent(child) is False: + uowcommit.register_object( + child, + isdelete=True, + operation="delete", + prop=self.prop, + ) + for c, m, st_, dct_ in self.mapper.cascade_iterator( + "delete", child + ): + uowcommit.register_object(st_, isdelete=True) + + if pks_changed: + if history: + for child in history.unchanged: + if child is not None: + uowcommit.register_object( + child, + False, + self.passive_updates, + operation="pk change", + prop=self.prop, + ) + + def process_deletes(self, uowcommit, states): + # head object is being deleted, and we manage its list of + # child objects the child objects have to have their foreign + # key to the parent set to NULL this phase can be called + # safely for any cascade but is unnecessary if delete cascade + # is on. + + if self.post_update or not self.passive_deletes == "all": + children_added = uowcommit.memo(("children_added", self), set) + + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + for child in history.deleted: + if ( + child is not None + and self.hasparent(child) is False + ): + self._synchronize( + state, child, None, True, uowcommit, False + ) + if self.post_update and child: + self._post_update(child, uowcommit, [state]) + + if self.post_update or not self.cascade.delete: + for child in set(history.unchanged).difference( + children_added + ): + if child is not None: + self._synchronize( + state, child, None, True, uowcommit, False + ) + if self.post_update and child: + self._post_update( + child, uowcommit, [state] + ) + + # technically, we can even remove each child from the + # collection here too. but this would be a somewhat + # inconsistent behavior since it wouldn't happen + # if the old parent wasn't deleted but child was moved. + + def process_saves(self, uowcommit, states): + should_null_fks = ( + not self.cascade.delete_orphan + and not self.passive_deletes == "all" + ) + + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, attributes.PASSIVE_NO_INITIALIZE + ) + if history: + for child in history.added: + self._synchronize( + state, child, None, False, uowcommit, False + ) + if child is not None and self.post_update: + self._post_update(child, uowcommit, [state]) + + for child in history.deleted: + if ( + should_null_fks + and not self.cascade.delete_orphan + and not self.hasparent(child) + ): + self._synchronize( + state, child, None, True, uowcommit, False + ) + + if self._pks_changed(uowcommit, state): + for child in history.unchanged: + self._synchronize( + state, child, None, False, uowcommit, True + ) + + def _synchronize( + self, state, child, associationrow, clearkeys, uowcommit, pks_changed + ): + source = state + dest = child + self._verify_canload(child) + if dest is None or ( + not self.post_update and uowcommit.is_deleted(dest) + ): + return + if clearkeys: + sync.clear(dest, self.mapper, self.prop.synchronize_pairs) + else: + sync.populate( + source, + self.parent, + dest, + self.mapper, + self.prop.synchronize_pairs, + uowcommit, + self.passive_updates and pks_changed, + ) + + def _pks_changed(self, uowcommit, state): + return sync.source_modified( + uowcommit, state, self.parent, self.prop.synchronize_pairs + ) + + +class ManyToOneDP(DependencyProcessor): + def __init__(self, prop): + DependencyProcessor.__init__(self, prop) + for mapper in self.mapper.self_and_descendants: + mapper._dependency_processors.append(DetectKeySwitch(prop)) + + def per_property_dependencies( + self, + uow, + parent_saves, + child_saves, + parent_deletes, + child_deletes, + after_save, + before_delete, + ): + if self.post_update: + parent_post_updates = unitofwork.PostUpdateAll( + uow, self.parent.primary_base_mapper, False + ) + parent_pre_updates = unitofwork.PostUpdateAll( + uow, self.parent.primary_base_mapper, True + ) + + uow.dependencies.update( + [ + (child_saves, after_save), + (parent_saves, after_save), + (after_save, parent_post_updates), + (after_save, parent_pre_updates), + (before_delete, parent_pre_updates), + (parent_pre_updates, child_deletes), + (parent_pre_updates, parent_deletes), + ] + ) + else: + uow.dependencies.update( + [ + (child_saves, after_save), + (after_save, parent_saves), + (parent_saves, child_deletes), + (parent_deletes, child_deletes), + ] + ) + + def per_state_dependencies( + self, + uow, + save_parent, + delete_parent, + child_action, + after_save, + before_delete, + isdelete, + childisdelete, + ): + if self.post_update: + if not isdelete: + parent_post_updates = unitofwork.PostUpdateAll( + uow, self.parent.primary_base_mapper, False + ) + if childisdelete: + uow.dependencies.update( + [ + (after_save, parent_post_updates), + (parent_post_updates, child_action), + ] + ) + else: + uow.dependencies.update( + [ + (save_parent, after_save), + (child_action, after_save), + (after_save, parent_post_updates), + ] + ) + else: + parent_pre_updates = unitofwork.PostUpdateAll( + uow, self.parent.primary_base_mapper, True + ) + + uow.dependencies.update( + [ + (before_delete, parent_pre_updates), + (parent_pre_updates, delete_parent), + (parent_pre_updates, child_action), + ] + ) + + elif not isdelete: + if not childisdelete: + uow.dependencies.update( + [(child_action, after_save), (after_save, save_parent)] + ) + else: + uow.dependencies.update([(after_save, save_parent)]) + + else: + if childisdelete: + uow.dependencies.update([(delete_parent, child_action)]) + + def presort_deletes(self, uowcommit, states): + if self.cascade.delete or self.cascade.delete_orphan: + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + if self.cascade.delete_orphan: + todelete = history.sum() + else: + todelete = history.non_deleted() + for child in todelete: + if child is None: + continue + uowcommit.register_object( + child, + isdelete=True, + operation="delete", + prop=self.prop, + ) + t = self.mapper.cascade_iterator("delete", child) + for c, m, st_, dct_ in t: + uowcommit.register_object(st_, isdelete=True) + + def presort_saves(self, uowcommit, states): + for state in states: + uowcommit.register_object(state, operation="add", prop=self.prop) + if self.cascade.delete_orphan: + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + for child in history.deleted: + if self.hasparent(child) is False: + uowcommit.register_object( + child, + isdelete=True, + operation="delete", + prop=self.prop, + ) + + t = self.mapper.cascade_iterator("delete", child) + for c, m, st_, dct_ in t: + uowcommit.register_object(st_, isdelete=True) + + def process_deletes(self, uowcommit, states): + if ( + self.post_update + and not self.cascade.delete_orphan + and not self.passive_deletes == "all" + ): + # post_update means we have to update our + # row to not reference the child object + # before we can DELETE the row + for state in states: + self._synchronize(state, None, None, True, uowcommit) + if state and self.post_update: + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + self._post_update( + state, uowcommit, history.sum(), is_m2o_delete=True + ) + + def process_saves(self, uowcommit, states): + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, attributes.PASSIVE_NO_INITIALIZE + ) + if history: + if history.added: + for child in history.added: + self._synchronize( + state, child, None, False, uowcommit, "add" + ) + elif history.deleted: + self._synchronize( + state, None, None, True, uowcommit, "delete" + ) + if self.post_update: + self._post_update(state, uowcommit, history.sum()) + + def _synchronize( + self, + state, + child, + associationrow, + clearkeys, + uowcommit, + operation=None, + ): + if state is None or ( + not self.post_update and uowcommit.is_deleted(state) + ): + return + + if ( + operation is not None + and child is not None + and not uowcommit.session._contains_state(child) + ): + util.warn( + "Object of type %s not in session, %s " + "operation along '%s' won't proceed" + % (mapperutil.state_class_str(child), operation, self.prop) + ) + return + + if clearkeys or child is None: + sync.clear(state, self.parent, self.prop.synchronize_pairs) + else: + self._verify_canload(child) + sync.populate( + child, + self.mapper, + state, + self.parent, + self.prop.synchronize_pairs, + uowcommit, + False, + ) + + +class DetectKeySwitch(DependencyProcessor): + """For many-to-one relationships with no one-to-many backref, + searches for parents through the unit of work when a primary + key has changed and updates them. + + Theoretically, this approach could be expanded to support transparent + deletion of objects referenced via many-to-one as well, although + the current attribute system doesn't do enough bookkeeping for this + to be efficient. + + """ + + def per_property_preprocessors(self, uow): + if self.prop._reverse_property: + if self.passive_updates: + return + else: + if False in ( + prop.passive_updates + for prop in self.prop._reverse_property + ): + return + + uow.register_preprocessor(self, False) + + def per_property_flush_actions(self, uow): + parent_saves = unitofwork.SaveUpdateAll(uow, self.parent.base_mapper) + after_save = unitofwork.ProcessAll(uow, self, False, False) + uow.dependencies.update([(parent_saves, after_save)]) + + def per_state_flush_actions(self, uow, states, isdelete): + pass + + def presort_deletes(self, uowcommit, states): + pass + + def presort_saves(self, uow, states): + if not self.passive_updates: + # for non-passive updates, register in the preprocess stage + # so that mapper save_obj() gets a hold of changes + self._process_key_switches(states, uow) + + def prop_has_changes(self, uow, states, isdelete): + if not isdelete and self.passive_updates: + d = self._key_switchers(uow, states) + return bool(d) + + return False + + def process_deletes(self, uowcommit, states): + assert False + + def process_saves(self, uowcommit, states): + # for passive updates, register objects in the process stage + # so that we avoid ManyToOneDP's registering the object without + # the listonly flag in its own preprocess stage (results in UPDATE) + # statements being emitted + assert self.passive_updates + self._process_key_switches(states, uowcommit) + + def _key_switchers(self, uow, states): + switched, notswitched = uow.memo( + ("pk_switchers", self), lambda: (set(), set()) + ) + + allstates = switched.union(notswitched) + for s in states: + if s not in allstates: + if self._pks_changed(uow, s): + switched.add(s) + else: + notswitched.add(s) + return switched + + def _process_key_switches(self, deplist, uowcommit): + switchers = self._key_switchers(uowcommit, deplist) + if switchers: + # if primary key values have actually changed somewhere, perform + # a linear search through the UOW in search of a parent. + for state in uowcommit.session.identity_map.all_states(): + if not issubclass(state.class_, self.parent.class_): + continue + dict_ = state.dict + related = state.get_impl(self.key).get( + state, dict_, passive=self._passive_update_flag + ) + if ( + related is not attributes.PASSIVE_NO_RESULT + and related is not None + ): + if self.prop.uselist: + if not related: + continue + related_obj = related[0] + else: + related_obj = related + related_state = attributes.instance_state(related_obj) + if related_state in switchers: + uowcommit.register_object( + state, False, self.passive_updates + ) + sync.populate( + related_state, + self.mapper, + state, + self.parent, + self.prop.synchronize_pairs, + uowcommit, + self.passive_updates, + ) + + def _pks_changed(self, uowcommit, state): + return bool(state.key) and sync.source_modified( + uowcommit, state, self.mapper, self.prop.synchronize_pairs + ) + + +class ManyToManyDP(DependencyProcessor): + def per_property_dependencies( + self, + uow, + parent_saves, + child_saves, + parent_deletes, + child_deletes, + after_save, + before_delete, + ): + uow.dependencies.update( + [ + (parent_saves, after_save), + (child_saves, after_save), + (after_save, child_deletes), + # a rowswitch on the parent from deleted to saved + # can make this one occur, as the "save" may remove + # an element from the + # "deleted" list before we have a chance to + # process its child rows + (before_delete, parent_saves), + (before_delete, parent_deletes), + (before_delete, child_deletes), + (before_delete, child_saves), + ] + ) + + def per_state_dependencies( + self, + uow, + save_parent, + delete_parent, + child_action, + after_save, + before_delete, + isdelete, + childisdelete, + ): + if not isdelete: + if childisdelete: + uow.dependencies.update( + [(save_parent, after_save), (after_save, child_action)] + ) + else: + uow.dependencies.update( + [(save_parent, after_save), (child_action, after_save)] + ) + else: + uow.dependencies.update( + [(before_delete, child_action), (before_delete, delete_parent)] + ) + + def presort_deletes(self, uowcommit, states): + # TODO: no tests fail if this whole + # thing is removed !!!! + if not self.passive_deletes: + # if no passive deletes, load history on + # the collection, so that prop_has_changes() + # returns True + for state in states: + uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + + def presort_saves(self, uowcommit, states): + if not self.passive_updates: + # if no passive updates, load history on + # each collection where parent has changed PK, + # so that prop_has_changes() returns True + for state in states: + if self._pks_changed(uowcommit, state): + uowcommit.get_attribute_history( + state, self.key, attributes.PASSIVE_OFF + ) + + if not self.cascade.delete_orphan: + return + + # check for child items removed from the collection + # if delete_orphan check is turned on. + for state in states: + history = uowcommit.get_attribute_history( + state, self.key, attributes.PASSIVE_NO_INITIALIZE + ) + if history: + for child in history.deleted: + if self.hasparent(child) is False: + uowcommit.register_object( + child, + isdelete=True, + operation="delete", + prop=self.prop, + ) + for c, m, st_, dct_ in self.mapper.cascade_iterator( + "delete", child + ): + uowcommit.register_object(st_, isdelete=True) + + def process_deletes(self, uowcommit, states): + secondary_delete = [] + secondary_insert = [] + secondary_update = [] + + processed = self._get_reversed_processed_set(uowcommit) + tmp = set() + for state in states: + # this history should be cached already, as + # we loaded it in preprocess_deletes + history = uowcommit.get_attribute_history( + state, self.key, self._passive_delete_flag + ) + if history: + for child in history.non_added(): + if child is None or ( + processed is not None and (state, child) in processed + ): + continue + associationrow = {} + if not self._synchronize( + state, + child, + associationrow, + False, + uowcommit, + "delete", + ): + continue + secondary_delete.append(associationrow) + + tmp.update((c, state) for c in history.non_added()) + + if processed is not None: + processed.update(tmp) + + self._run_crud( + uowcommit, secondary_insert, secondary_update, secondary_delete + ) + + def process_saves(self, uowcommit, states): + secondary_delete = [] + secondary_insert = [] + secondary_update = [] + + processed = self._get_reversed_processed_set(uowcommit) + tmp = set() + + for state in states: + need_cascade_pks = not self.passive_updates and self._pks_changed( + uowcommit, state + ) + if need_cascade_pks: + passive = ( + attributes.PASSIVE_OFF + | attributes.INCLUDE_PENDING_MUTATIONS + ) + else: + passive = ( + attributes.PASSIVE_NO_INITIALIZE + | attributes.INCLUDE_PENDING_MUTATIONS + ) + history = uowcommit.get_attribute_history(state, self.key, passive) + if history: + for child in history.added: + if processed is not None and (state, child) in processed: + continue + associationrow = {} + if not self._synchronize( + state, child, associationrow, False, uowcommit, "add" + ): + continue + secondary_insert.append(associationrow) + for child in history.deleted: + if processed is not None and (state, child) in processed: + continue + associationrow = {} + if not self._synchronize( + state, + child, + associationrow, + False, + uowcommit, + "delete", + ): + continue + secondary_delete.append(associationrow) + + tmp.update((c, state) for c in history.added + history.deleted) + + if need_cascade_pks: + for child in history.unchanged: + associationrow = {} + sync.update( + state, + self.parent, + associationrow, + "old_", + self.prop.synchronize_pairs, + ) + sync.update( + child, + self.mapper, + associationrow, + "old_", + self.prop.secondary_synchronize_pairs, + ) + + secondary_update.append(associationrow) + + if processed is not None: + processed.update(tmp) + + self._run_crud( + uowcommit, secondary_insert, secondary_update, secondary_delete + ) + + def _run_crud( + self, uowcommit, secondary_insert, secondary_update, secondary_delete + ): + connection = uowcommit.transaction.connection(self.mapper) + + if secondary_delete: + associationrow = secondary_delete[0] + statement = self.secondary.delete().where( + sql.and_( + *[ + c == sql.bindparam(c.key, type_=c.type) + for c in self.secondary.c + if c.key in associationrow + ] + ) + ) + result = connection.execute(statement, secondary_delete) + + if ( + result.supports_sane_multi_rowcount() + ) and result.rowcount != len(secondary_delete): + raise exc.StaleDataError( + "DELETE statement on table '%s' expected to delete " + "%d row(s); Only %d were matched." + % ( + self.secondary.description, + len(secondary_delete), + result.rowcount, + ) + ) + + if secondary_update: + associationrow = secondary_update[0] + statement = self.secondary.update().where( + sql.and_( + *[ + c == sql.bindparam("old_" + c.key, type_=c.type) + for c in self.secondary.c + if c.key in associationrow + ] + ) + ) + result = connection.execute(statement, secondary_update) + + if ( + result.supports_sane_multi_rowcount() + ) and result.rowcount != len(secondary_update): + raise exc.StaleDataError( + "UPDATE statement on table '%s' expected to update " + "%d row(s); Only %d were matched." + % ( + self.secondary.description, + len(secondary_update), + result.rowcount, + ) + ) + + if secondary_insert: + statement = self.secondary.insert() + connection.execute(statement, secondary_insert) + + def _synchronize( + self, state, child, associationrow, clearkeys, uowcommit, operation + ): + # this checks for None if uselist=True + self._verify_canload(child) + + # but if uselist=False we get here. If child is None, + # no association row can be generated, so return. + if child is None: + return False + + if child is not None and not uowcommit.session._contains_state(child): + if not child.deleted: + util.warn( + "Object of type %s not in session, %s " + "operation along '%s' won't proceed" + % (mapperutil.state_class_str(child), operation, self.prop) + ) + return False + + sync.populate_dict( + state, self.parent, associationrow, self.prop.synchronize_pairs + ) + sync.populate_dict( + child, + self.mapper, + associationrow, + self.prop.secondary_synchronize_pairs, + ) + + return True + + def _pks_changed(self, uowcommit, state): + return sync.source_modified( + uowcommit, state, self.parent, self.prop.synchronize_pairs + ) + + +_direction_to_processor = { + ONETOMANY: OneToManyDP, + MANYTOONE: ManyToOneDP, + MANYTOMANY: ManyToManyDP, +} diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/descriptor_props.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/descriptor_props.py new file mode 100644 index 0000000000000000000000000000000000000000..c6bae2debd945d589afe9dfa7aad716c4e52b5cd --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/descriptor_props.py @@ -0,0 +1,1092 @@ +# orm/descriptor_props.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""Descriptor properties are more "auxiliary" properties +that exist as configurational elements, but don't participate +as actively in the load/persist ORM loop. + +""" +from __future__ import annotations + +from dataclasses import is_dataclass +import inspect +import itertools +import operator +import typing +from typing import Any +from typing import Callable +from typing import Dict +from typing import List +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import attributes +from . import util as orm_util +from .base import _DeclarativeMapped +from .base import LoaderCallableStatus +from .base import Mapped +from .base import PassiveFlag +from .base import SQLORMOperations +from .interfaces import _AttributeOptions +from .interfaces import _IntrospectsAnnotations +from .interfaces import _MapsColumns +from .interfaces import MapperProperty +from .interfaces import PropComparator +from .util import _none_set +from .util import de_stringify_annotation +from .. import event +from .. import exc as sa_exc +from .. import schema +from .. import sql +from .. import util +from ..sql import expression +from ..sql import operators +from ..sql.elements import BindParameter +from ..util.typing import get_args +from ..util.typing import is_fwd_ref +from ..util.typing import is_pep593 + + +if typing.TYPE_CHECKING: + from ._typing import _InstanceDict + from ._typing import _RegistryType + from .attributes import History + from .attributes import InstrumentedAttribute + from .attributes import QueryableAttribute + from .context import ORMCompileState + from .decl_base import _ClassScanMapperConfig + from .mapper import Mapper + from .properties import ColumnProperty + from .properties import MappedColumn + from .state import InstanceState + from ..engine.base import Connection + from ..engine.row import Row + from ..sql._typing import _DMLColumnArgument + from ..sql._typing import _InfoType + from ..sql.elements import ClauseList + from ..sql.elements import ColumnElement + from ..sql.operators import OperatorType + from ..sql.schema import Column + from ..sql.selectable import Select + from ..util.typing import _AnnotationScanType + from ..util.typing import CallableReference + from ..util.typing import DescriptorReference + from ..util.typing import RODescriptorReference + +_T = TypeVar("_T", bound=Any) +_PT = TypeVar("_PT", bound=Any) + + +class DescriptorProperty(MapperProperty[_T]): + """:class:`.MapperProperty` which proxies access to a + user-defined descriptor.""" + + doc: Optional[str] = None + + uses_objects = False + _links_to_entity = False + + descriptor: DescriptorReference[Any] + + def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]: + raise NotImplementedError( + "This MapperProperty does not implement column loader strategies" + ) + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + ) -> History: + raise NotImplementedError() + + def instrument_class(self, mapper: Mapper[Any]) -> None: + prop = self + + class _ProxyImpl(attributes.AttributeImpl): + accepts_scalar_loader = False + load_on_unexpire = True + collection = False + + @property + def uses_objects(self) -> bool: # type: ignore + return prop.uses_objects + + def __init__(self, key: str): + self.key = key + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + ) -> History: + return prop.get_history(state, dict_, passive) + + if self.descriptor is None: + desc = getattr(mapper.class_, self.key, None) + if mapper._is_userland_descriptor(self.key, desc): + self.descriptor = desc + + if self.descriptor is None: + + def fset(obj: Any, value: Any) -> None: + setattr(obj, self.name, value) + + def fdel(obj: Any) -> None: + delattr(obj, self.name) + + def fget(obj: Any) -> Any: + return getattr(obj, self.name) + + self.descriptor = property(fget=fget, fset=fset, fdel=fdel) + + proxy_attr = attributes.create_proxied_attribute(self.descriptor)( + self.parent.class_, + self.key, + self.descriptor, + lambda: self._comparator_factory(mapper), + doc=self.doc, + original_property=self, + ) + proxy_attr.impl = _ProxyImpl(self.key) + mapper.class_manager.instrument_attribute(self.key, proxy_attr) + + +_CompositeAttrType = Union[ + str, + "Column[_T]", + "MappedColumn[_T]", + "InstrumentedAttribute[_T]", + "Mapped[_T]", +] + + +_CC = TypeVar("_CC", bound=Any) + + +_composite_getters: weakref.WeakKeyDictionary[ + Type[Any], Callable[[Any], Tuple[Any, ...]] +] = weakref.WeakKeyDictionary() + + +class CompositeProperty( + _MapsColumns[_CC], _IntrospectsAnnotations, DescriptorProperty[_CC] +): + """Defines a "composite" mapped attribute, representing a collection + of columns as one attribute. + + :class:`.CompositeProperty` is constructed using the :func:`.composite` + function. + + .. seealso:: + + :ref:`mapper_composite` + + """ + + composite_class: Union[Type[_CC], Callable[..., _CC]] + attrs: Tuple[_CompositeAttrType[Any], ...] + + _generated_composite_accessor: CallableReference[ + Optional[Callable[[_CC], Tuple[Any, ...]]] + ] + + comparator_factory: Type[Comparator[_CC]] + + def __init__( + self, + _class_or_attr: Union[ + None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any] + ] = None, + *attrs: _CompositeAttrType[Any], + attribute_options: Optional[_AttributeOptions] = None, + active_history: bool = False, + deferred: bool = False, + group: Optional[str] = None, + comparator_factory: Optional[Type[Comparator[_CC]]] = None, + info: Optional[_InfoType] = None, + **kwargs: Any, + ): + super().__init__(attribute_options=attribute_options) + + if isinstance(_class_or_attr, (Mapped, str, sql.ColumnElement)): + self.attrs = (_class_or_attr,) + attrs + # will initialize within declarative_scan + self.composite_class = None # type: ignore + else: + self.composite_class = _class_or_attr # type: ignore + self.attrs = attrs + + self.active_history = active_history + self.deferred = deferred + self.group = group + self.comparator_factory = ( + comparator_factory + if comparator_factory is not None + else self.__class__.Comparator + ) + self._generated_composite_accessor = None + if info is not None: + self.info.update(info) + + util.set_creation_order(self) + self._create_descriptor() + self._init_accessor() + + def instrument_class(self, mapper: Mapper[Any]) -> None: + super().instrument_class(mapper) + self._setup_event_handlers() + + def _composite_values_from_instance(self, value: _CC) -> Tuple[Any, ...]: + if self._generated_composite_accessor: + return self._generated_composite_accessor(value) + else: + try: + accessor = value.__composite_values__ + except AttributeError as ae: + raise sa_exc.InvalidRequestError( + f"Composite class {self.composite_class.__name__} is not " + f"a dataclass and does not define a __composite_values__()" + " method; can't get state" + ) from ae + else: + return accessor() # type: ignore + + def do_init(self) -> None: + """Initialization which occurs after the :class:`.Composite` + has been associated with its parent mapper. + + """ + self._setup_arguments_on_columns() + + _COMPOSITE_FGET = object() + + def _create_descriptor(self) -> None: + """Create the Python descriptor that will serve as + the access point on instances of the mapped class. + + """ + + def fget(instance: Any) -> Any: + dict_ = attributes.instance_dict(instance) + state = attributes.instance_state(instance) + + if self.key not in dict_: + # key not present. Iterate through related + # attributes, retrieve their values. This + # ensures they all load. + values = [ + getattr(instance, key) for key in self._attribute_keys + ] + + # current expected behavior here is that the composite is + # created on access if the object is persistent or if + # col attributes have non-None. This would be better + # if the composite were created unconditionally, + # but that would be a behavioral change. + if self.key not in dict_ and ( + state.key is not None or not _none_set.issuperset(values) + ): + dict_[self.key] = self.composite_class(*values) + state.manager.dispatch.refresh( + state, self._COMPOSITE_FGET, [self.key] + ) + + return dict_.get(self.key, None) + + def fset(instance: Any, value: Any) -> None: + dict_ = attributes.instance_dict(instance) + state = attributes.instance_state(instance) + attr = state.manager[self.key] + + if attr.dispatch._active_history: + previous = fget(instance) + else: + previous = dict_.get(self.key, LoaderCallableStatus.NO_VALUE) + + for fn in attr.dispatch.set: + value = fn(state, value, previous, attr.impl) + dict_[self.key] = value + if value is None: + for key in self._attribute_keys: + setattr(instance, key, None) + else: + for key, value in zip( + self._attribute_keys, + self._composite_values_from_instance(value), + ): + setattr(instance, key, value) + + def fdel(instance: Any) -> None: + state = attributes.instance_state(instance) + dict_ = attributes.instance_dict(instance) + attr = state.manager[self.key] + + if attr.dispatch._active_history: + previous = fget(instance) + dict_.pop(self.key, None) + else: + previous = dict_.pop(self.key, LoaderCallableStatus.NO_VALUE) + + attr = state.manager[self.key] + attr.dispatch.remove(state, previous, attr.impl) + for key in self._attribute_keys: + setattr(instance, key, None) + + self.descriptor = property(fget, fset, fdel) + + @util.preload_module("sqlalchemy.orm.properties") + def declarative_scan( + self, + decl_scan: _ClassScanMapperConfig, + registry: _RegistryType, + cls: Type[Any], + originating_module: Optional[str], + key: str, + mapped_container: Optional[Type[Mapped[Any]]], + annotation: Optional[_AnnotationScanType], + extracted_mapped_annotation: Optional[_AnnotationScanType], + is_dataclass_field: bool, + ) -> None: + MappedColumn = util.preloaded.orm_properties.MappedColumn + if ( + self.composite_class is None + and extracted_mapped_annotation is None + ): + self._raise_for_required(key, cls) + argument = extracted_mapped_annotation + + if is_pep593(argument): + argument = get_args(argument)[0] + + if argument and self.composite_class is None: + if isinstance(argument, str) or is_fwd_ref( + argument, check_generic=True + ): + if originating_module is None: + str_arg = ( + argument.__forward_arg__ + if hasattr(argument, "__forward_arg__") + else str(argument) + ) + raise sa_exc.ArgumentError( + f"Can't use forward ref {argument} for composite " + f"class argument; set up the type as Mapped[{str_arg}]" + ) + argument = de_stringify_annotation( + cls, argument, originating_module, include_generic=True + ) + + self.composite_class = argument + + if is_dataclass(self.composite_class): + self._setup_for_dataclass( + decl_scan, registry, cls, originating_module, key + ) + else: + for attr in self.attrs: + if ( + isinstance(attr, (MappedColumn, schema.Column)) + and attr.name is None + ): + raise sa_exc.ArgumentError( + "Composite class column arguments must be named " + "unless a dataclass is used" + ) + self._init_accessor() + + def _init_accessor(self) -> None: + if is_dataclass(self.composite_class) and not hasattr( + self.composite_class, "__composite_values__" + ): + insp = inspect.signature(self.composite_class) + getter = operator.attrgetter( + *[p.name for p in insp.parameters.values()] + ) + if len(insp.parameters) == 1: + self._generated_composite_accessor = lambda obj: (getter(obj),) + else: + self._generated_composite_accessor = getter + + if ( + self.composite_class is not None + and isinstance(self.composite_class, type) + and self.composite_class not in _composite_getters + ): + if self._generated_composite_accessor is not None: + _composite_getters[self.composite_class] = ( + self._generated_composite_accessor + ) + elif hasattr(self.composite_class, "__composite_values__"): + _composite_getters[self.composite_class] = ( + lambda obj: obj.__composite_values__() + ) + + @util.preload_module("sqlalchemy.orm.properties") + @util.preload_module("sqlalchemy.orm.decl_base") + def _setup_for_dataclass( + self, + decl_scan: _ClassScanMapperConfig, + registry: _RegistryType, + cls: Type[Any], + originating_module: Optional[str], + key: str, + ) -> None: + MappedColumn = util.preloaded.orm_properties.MappedColumn + + decl_base = util.preloaded.orm_decl_base + + insp = inspect.signature(self.composite_class) + for param, attr in itertools.zip_longest( + insp.parameters.values(), self.attrs + ): + if param is None: + raise sa_exc.ArgumentError( + f"number of composite attributes " + f"{len(self.attrs)} exceeds " + f"that of the number of attributes in class " + f"{self.composite_class.__name__} {len(insp.parameters)}" + ) + if attr is None: + # fill in missing attr spots with empty MappedColumn + attr = MappedColumn() + self.attrs += (attr,) + + if isinstance(attr, MappedColumn): + attr.declarative_scan_for_composite( + decl_scan, + registry, + cls, + originating_module, + key, + param.name, + param.annotation, + ) + elif isinstance(attr, schema.Column): + decl_base._undefer_column_name(param.name, attr) + + @util.memoized_property + def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]: + return [getattr(self.parent.class_, prop.key) for prop in self.props] + + @util.memoized_property + @util.preload_module("orm.properties") + def props(self) -> Sequence[MapperProperty[Any]]: + props = [] + MappedColumn = util.preloaded.orm_properties.MappedColumn + + for attr in self.attrs: + if isinstance(attr, str): + prop = self.parent.get_property(attr, _configure_mappers=False) + elif isinstance(attr, schema.Column): + prop = self.parent._columntoproperty[attr] + elif isinstance(attr, MappedColumn): + prop = self.parent._columntoproperty[attr.column] + elif isinstance(attr, attributes.InstrumentedAttribute): + prop = attr.property + else: + prop = None + + if not isinstance(prop, MapperProperty): + raise sa_exc.ArgumentError( + "Composite expects Column objects or mapped " + f"attributes/attribute names as arguments, got: {attr!r}" + ) + + props.append(prop) + return props + + def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]: + return self._comparable_elements + + @util.non_memoized_property + @util.preload_module("orm.properties") + def columns(self) -> Sequence[Column[Any]]: + MappedColumn = util.preloaded.orm_properties.MappedColumn + return [ + a.column if isinstance(a, MappedColumn) else a + for a in self.attrs + if isinstance(a, (schema.Column, MappedColumn)) + ] + + @property + def mapper_property_to_assign(self) -> Optional[MapperProperty[_CC]]: + return self + + @property + def columns_to_assign(self) -> List[Tuple[schema.Column[Any], int]]: + return [(c, 0) for c in self.columns if c.table is None] + + @util.preload_module("orm.properties") + def _setup_arguments_on_columns(self) -> None: + """Propagate configuration arguments made on this composite + to the target columns, for those that apply. + + """ + ColumnProperty = util.preloaded.orm_properties.ColumnProperty + + for prop in self.props: + if not isinstance(prop, ColumnProperty): + continue + else: + cprop = prop + + cprop.active_history = self.active_history + if self.deferred: + cprop.deferred = self.deferred + cprop.strategy_key = (("deferred", True), ("instrument", True)) + cprop.group = self.group + + def _setup_event_handlers(self) -> None: + """Establish events that populate/expire the composite attribute.""" + + def load_handler( + state: InstanceState[Any], context: ORMCompileState + ) -> None: + _load_refresh_handler(state, context, None, is_refresh=False) + + def refresh_handler( + state: InstanceState[Any], + context: ORMCompileState, + to_load: Optional[Sequence[str]], + ) -> None: + # note this corresponds to sqlalchemy.ext.mutable load_attrs() + + if not to_load or ( + {self.key}.union(self._attribute_keys) + ).intersection(to_load): + _load_refresh_handler(state, context, to_load, is_refresh=True) + + def _load_refresh_handler( + state: InstanceState[Any], + context: ORMCompileState, + to_load: Optional[Sequence[str]], + is_refresh: bool, + ) -> None: + dict_ = state.dict + + # if context indicates we are coming from the + # fget() handler, this already set the value; skip the + # handler here. (other handlers like mutablecomposite will still + # want to catch it) + # there's an insufficiency here in that the fget() handler + # really should not be using the refresh event and there should + # be some other event that mutablecomposite can subscribe + # towards for this. + + if ( + not is_refresh or context is self._COMPOSITE_FGET + ) and self.key in dict_: + return + + # if column elements aren't loaded, skip. + # __get__() will initiate a load for those + # columns + for k in self._attribute_keys: + if k not in dict_: + return + + dict_[self.key] = self.composite_class( + *[state.dict[key] for key in self._attribute_keys] + ) + + def expire_handler( + state: InstanceState[Any], keys: Optional[Sequence[str]] + ) -> None: + if keys is None or set(self._attribute_keys).intersection(keys): + state.dict.pop(self.key, None) + + def insert_update_handler( + mapper: Mapper[Any], + connection: Connection, + state: InstanceState[Any], + ) -> None: + """After an insert or update, some columns may be expired due + to server side defaults, or re-populated due to client side + defaults. Pop out the composite value here so that it + recreates. + + """ + + state.dict.pop(self.key, None) + + event.listen( + self.parent, "after_insert", insert_update_handler, raw=True + ) + event.listen( + self.parent, "after_update", insert_update_handler, raw=True + ) + event.listen( + self.parent, "load", load_handler, raw=True, propagate=True + ) + event.listen( + self.parent, "refresh", refresh_handler, raw=True, propagate=True + ) + event.listen( + self.parent, "expire", expire_handler, raw=True, propagate=True + ) + + proxy_attr = self.parent.class_manager[self.key] + proxy_attr.impl.dispatch = proxy_attr.dispatch # type: ignore + proxy_attr.impl.dispatch._active_history = self.active_history + + # TODO: need a deserialize hook here + + @util.memoized_property + def _attribute_keys(self) -> Sequence[str]: + return [prop.key for prop in self.props] + + def _populate_composite_bulk_save_mappings_fn( + self, + ) -> Callable[[Dict[str, Any]], None]: + if self._generated_composite_accessor: + get_values = self._generated_composite_accessor + else: + + def get_values(val: Any) -> Tuple[Any]: + return val.__composite_values__() # type: ignore + + attrs = [prop.key for prop in self.props] + + def populate(dest_dict: Dict[str, Any]) -> None: + dest_dict.update( + { + key: val + for key, val in zip( + attrs, get_values(dest_dict.pop(self.key)) + ) + } + ) + + return populate + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + ) -> History: + """Provided for userland code that uses attributes.get_history().""" + + added: List[Any] = [] + deleted: List[Any] = [] + + has_history = False + for prop in self.props: + key = prop.key + hist = state.manager[key].impl.get_history(state, dict_) + if hist.has_changes(): + has_history = True + + non_deleted = hist.non_deleted() + if non_deleted: + added.extend(non_deleted) + else: + added.append(None) + if hist.deleted: + deleted.extend(hist.deleted) + else: + deleted.append(None) + + if has_history: + return attributes.History( + [self.composite_class(*added)], + (), + [self.composite_class(*deleted)], + ) + else: + return attributes.History((), [self.composite_class(*added)], ()) + + def _comparator_factory( + self, mapper: Mapper[Any] + ) -> Composite.Comparator[_CC]: + return self.comparator_factory(self, mapper) + + class CompositeBundle(orm_util.Bundle[_T]): + def __init__( + self, + property_: Composite[_T], + expr: ClauseList, + ): + self.property = property_ + super().__init__(property_.key, *expr) + + def create_row_processor( + self, + query: Select[Any], + procs: Sequence[Callable[[Row[Any]], Any]], + labels: Sequence[str], + ) -> Callable[[Row[Any]], Any]: + def proc(row: Row[Any]) -> Any: + return self.property.composite_class( + *[proc(row) for proc in procs] + ) + + return proc + + class Comparator(PropComparator[_PT]): + """Produce boolean, comparison, and other operators for + :class:`.Composite` attributes. + + See the example in :ref:`composite_operations` for an overview + of usage , as well as the documentation for :class:`.PropComparator`. + + .. seealso:: + + :class:`.PropComparator` + + :class:`.ColumnOperators` + + :ref:`types_operators` + + :attr:`.TypeEngine.comparator_factory` + + """ + + # https://github.com/python/mypy/issues/4266 + __hash__ = None # type: ignore + + prop: RODescriptorReference[Composite[_PT]] + + @util.memoized_property + def clauses(self) -> ClauseList: + return expression.ClauseList( + group=False, *self._comparable_elements + ) + + def __clause_element__(self) -> CompositeProperty.CompositeBundle[_PT]: + return self.expression + + @util.memoized_property + def expression(self) -> CompositeProperty.CompositeBundle[_PT]: + clauses = self.clauses._annotate( + { + "parententity": self._parententity, + "parentmapper": self._parententity, + "proxy_key": self.prop.key, + } + ) + return CompositeProperty.CompositeBundle(self.prop, clauses) + + def _bulk_update_tuples( + self, value: Any + ) -> Sequence[Tuple[_DMLColumnArgument, Any]]: + if isinstance(value, BindParameter): + value = value.value + + values: Sequence[Any] + + if value is None: + values = [None for key in self.prop._attribute_keys] + elif isinstance(self.prop.composite_class, type) and isinstance( + value, self.prop.composite_class + ): + values = self.prop._composite_values_from_instance( + value # type: ignore[arg-type] + ) + else: + raise sa_exc.ArgumentError( + "Can't UPDATE composite attribute %s to %r" + % (self.prop, value) + ) + + return list(zip(self._comparable_elements, values)) + + @util.memoized_property + def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]: + if self._adapt_to_entity: + return [ + getattr(self._adapt_to_entity.entity, prop.key) + for prop in self.prop._comparable_elements + ] + else: + return self.prop._comparable_elements + + def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + return self._compare(operators.eq, other) + + def __ne__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 + return self._compare(operators.ne, other) + + def __lt__(self, other: Any) -> ColumnElement[bool]: + return self._compare(operators.lt, other) + + def __gt__(self, other: Any) -> ColumnElement[bool]: + return self._compare(operators.gt, other) + + def __le__(self, other: Any) -> ColumnElement[bool]: + return self._compare(operators.le, other) + + def __ge__(self, other: Any) -> ColumnElement[bool]: + return self._compare(operators.ge, other) + + # what might be interesting would be if we create + # an instance of the composite class itself with + # the columns as data members, then use "hybrid style" comparison + # to create these comparisons. then your Point.__eq__() method could + # be where comparison behavior is defined for SQL also. Likely + # not a good choice for default behavior though, not clear how it would + # work w/ dataclasses, etc. also no demand for any of this anyway. + def _compare( + self, operator: OperatorType, other: Any + ) -> ColumnElement[bool]: + values: Sequence[Any] + if other is None: + values = [None] * len(self.prop._comparable_elements) + else: + values = self.prop._composite_values_from_instance(other) + comparisons = [ + operator(a, b) + for a, b in zip(self.prop._comparable_elements, values) + ] + if self._adapt_to_entity: + assert self.adapter is not None + comparisons = [self.adapter(x) for x in comparisons] + return sql.and_(*comparisons) + + def __str__(self) -> str: + return str(self.parent.class_.__name__) + "." + self.key + + +class Composite(CompositeProperty[_T], _DeclarativeMapped[_T]): + """Declarative-compatible front-end for the :class:`.CompositeProperty` + class. + + Public constructor is the :func:`_orm.composite` function. + + .. versionchanged:: 2.0 Added :class:`_orm.Composite` as a Declarative + compatible subclass of :class:`_orm.CompositeProperty`. + + .. seealso:: + + :ref:`mapper_composite` + + """ + + inherit_cache = True + """:meta private:""" + + +class ConcreteInheritedProperty(DescriptorProperty[_T]): + """A 'do nothing' :class:`.MapperProperty` that disables + an attribute on a concrete subclass that is only present + on the inherited mapper, not the concrete classes' mapper. + + Cases where this occurs include: + + * When the superclass mapper is mapped against a + "polymorphic union", which includes all attributes from + all subclasses. + * When a relationship() is configured on an inherited mapper, + but not on the subclass mapper. Concrete mappers require + that relationship() is configured explicitly on each + subclass. + + """ + + def _comparator_factory( + self, mapper: Mapper[Any] + ) -> Type[PropComparator[_T]]: + comparator_callable = None + + for m in self.parent.iterate_to_root(): + p = m._props[self.key] + if getattr(p, "comparator_factory", None) is not None: + comparator_callable = p.comparator_factory + break + assert comparator_callable is not None + return comparator_callable(p, mapper) # type: ignore + + def __init__(self) -> None: + super().__init__() + + def warn() -> NoReturn: + raise AttributeError( + "Concrete %s does not implement " + "attribute %r at the instance level. Add " + "this property explicitly to %s." + % (self.parent, self.key, self.parent) + ) + + class NoninheritedConcreteProp: + def __set__(s: Any, obj: Any, value: Any) -> NoReturn: + warn() + + def __delete__(s: Any, obj: Any) -> NoReturn: + warn() + + def __get__(s: Any, obj: Any, owner: Any) -> Any: + if obj is None: + return self.descriptor + warn() + + self.descriptor = NoninheritedConcreteProp() + + +class SynonymProperty(DescriptorProperty[_T]): + """Denote an attribute name as a synonym to a mapped property, + in that the attribute will mirror the value and expression behavior + of another attribute. + + :class:`.Synonym` is constructed using the :func:`_orm.synonym` + function. + + .. seealso:: + + :ref:`synonyms` - Overview of synonyms + + """ + + comparator_factory: Optional[Type[PropComparator[_T]]] + + def __init__( + self, + name: str, + map_column: Optional[bool] = None, + descriptor: Optional[Any] = None, + comparator_factory: Optional[Type[PropComparator[_T]]] = None, + attribute_options: Optional[_AttributeOptions] = None, + info: Optional[_InfoType] = None, + doc: Optional[str] = None, + ): + super().__init__(attribute_options=attribute_options) + + self.name = name + self.map_column = map_column + self.descriptor = descriptor + self.comparator_factory = comparator_factory + if doc: + self.doc = doc + elif descriptor and descriptor.__doc__: + self.doc = descriptor.__doc__ + else: + self.doc = None + if info: + self.info.update(info) + + util.set_creation_order(self) + + if not TYPE_CHECKING: + + @property + def uses_objects(self) -> bool: + return getattr(self.parent.class_, self.name).impl.uses_objects + + # TODO: when initialized, check _proxied_object, + # emit a warning if its not a column-based property + + @util.memoized_property + def _proxied_object( + self, + ) -> Union[MapperProperty[_T], SQLORMOperations[_T]]: + attr = getattr(self.parent.class_, self.name) + if not hasattr(attr, "property") or not isinstance( + attr.property, MapperProperty + ): + # attribute is a non-MapperProprerty proxy such as + # hybrid or association proxy + if isinstance(attr, attributes.QueryableAttribute): + return attr.comparator + elif isinstance(attr, SQLORMOperations): + # association proxy comes here + return attr + + raise sa_exc.InvalidRequestError( + """synonym() attribute "%s.%s" only supports """ + """ORM mapped attributes, got %r""" + % (self.parent.class_.__name__, self.name, attr) + ) + return attr.property + + def _column_strategy_attrs(self) -> Sequence[QueryableAttribute[Any]]: + return (getattr(self.parent.class_, self.name),) + + def _comparator_factory(self, mapper: Mapper[Any]) -> SQLORMOperations[_T]: + prop = self._proxied_object + + if isinstance(prop, MapperProperty): + if self.comparator_factory: + comp = self.comparator_factory(prop, mapper) + else: + comp = prop.comparator_factory(prop, mapper) + return comp + else: + return prop + + def get_history( + self, + state: InstanceState[Any], + dict_: _InstanceDict, + passive: PassiveFlag = PassiveFlag.PASSIVE_OFF, + ) -> History: + attr: QueryableAttribute[Any] = getattr(self.parent.class_, self.name) + return attr.impl.get_history(state, dict_, passive=passive) + + @util.preload_module("sqlalchemy.orm.properties") + def set_parent(self, parent: Mapper[Any], init: bool) -> None: + properties = util.preloaded.orm_properties + + if self.map_column: + # implement the 'map_column' option. + if self.key not in parent.persist_selectable.c: + raise sa_exc.ArgumentError( + "Can't compile synonym '%s': no column on table " + "'%s' named '%s'" + % ( + self.name, + parent.persist_selectable.description, + self.key, + ) + ) + elif ( + parent.persist_selectable.c[self.key] + in parent._columntoproperty + and parent._columntoproperty[ + parent.persist_selectable.c[self.key] + ].key + == self.name + ): + raise sa_exc.ArgumentError( + "Can't call map_column=True for synonym %r=%r, " + "a ColumnProperty already exists keyed to the name " + "%r for column %r" + % (self.key, self.name, self.name, self.key) + ) + p: ColumnProperty[Any] = properties.ColumnProperty( + parent.persist_selectable.c[self.key] + ) + parent._configure_property(self.name, p, init=init, setparent=True) + p._mapped_by_synonym = self.key + + self.parent = parent + + +class Synonym(SynonymProperty[_T], _DeclarativeMapped[_T]): + """Declarative front-end for the :class:`.SynonymProperty` class. + + Public constructor is the :func:`_orm.synonym` function. + + .. versionchanged:: 2.0 Added :class:`_orm.Synonym` as a Declarative + compatible subclass for :class:`_orm.SynonymProperty` + + .. seealso:: + + :ref:`synonyms` - Overview of synonyms + + """ + + inherit_cache = True + """:meta private:""" diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/dynamic.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/dynamic.py new file mode 100644 index 0000000000000000000000000000000000000000..20eaa9fa8685d8a3f0e285581894c1c3caab0f48 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/dynamic.py @@ -0,0 +1,307 @@ +# orm/dynamic.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + + +"""Dynamic collection API. + +Dynamic collections act like Query() objects for read operations and support +basic add/delete mutation. + +.. legacy:: the "dynamic" loader is a legacy feature, superseded by the + "write_only" loader. + + +""" + +from __future__ import annotations + +from typing import Any +from typing import Iterable +from typing import Iterator +from typing import List +from typing import Optional +from typing import overload +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import attributes +from . import exc as orm_exc +from . import relationships +from . import util as orm_util +from .base import PassiveFlag +from .query import Query +from .session import object_session +from .writeonly import AbstractCollectionWriter +from .writeonly import WriteOnlyAttributeImpl +from .writeonly import WriteOnlyHistory +from .writeonly import WriteOnlyLoader +from .. import util +from ..engine import result + + +if TYPE_CHECKING: + from . import QueryableAttribute + from .mapper import Mapper + from .relationships import _RelationshipOrderByArg + from .session import Session + from .state import InstanceState + from .util import AliasedClass + from ..event import _Dispatch + from ..sql.elements import ColumnElement + +_T = TypeVar("_T", bound=Any) + + +class DynamicCollectionHistory(WriteOnlyHistory[_T]): + def __init__( + self, + attr: DynamicAttributeImpl, + state: InstanceState[_T], + passive: PassiveFlag, + apply_to: Optional[DynamicCollectionHistory[_T]] = None, + ) -> None: + if apply_to: + coll = AppenderQuery(attr, state).autoflush(False) + self.unchanged_items = util.OrderedIdentitySet(coll) + self.added_items = apply_to.added_items + self.deleted_items = apply_to.deleted_items + self._reconcile_collection = True + else: + self.deleted_items = util.OrderedIdentitySet() + self.added_items = util.OrderedIdentitySet() + self.unchanged_items = util.OrderedIdentitySet() + self._reconcile_collection = False + + +class DynamicAttributeImpl(WriteOnlyAttributeImpl): + _supports_dynamic_iteration = True + collection_history_cls = DynamicCollectionHistory[Any] + query_class: Type[AppenderMixin[Any]] # type: ignore[assignment] + + def __init__( + self, + class_: Union[Type[Any], AliasedClass[Any]], + key: str, + dispatch: _Dispatch[QueryableAttribute[Any]], + target_mapper: Mapper[_T], + order_by: _RelationshipOrderByArg, + query_class: Optional[Type[AppenderMixin[_T]]] = None, + **kw: Any, + ) -> None: + attributes.AttributeImpl.__init__( + self, class_, key, None, dispatch, **kw + ) + self.target_mapper = target_mapper + if order_by: + self.order_by = tuple(order_by) + if not query_class: + self.query_class = AppenderQuery + elif AppenderMixin in query_class.mro(): + self.query_class = query_class + else: + self.query_class = mixin_user_query(query_class) + + +@relationships.RelationshipProperty.strategy_for(lazy="dynamic") +class DynaLoader(WriteOnlyLoader): + impl_class = DynamicAttributeImpl + + +class AppenderMixin(AbstractCollectionWriter[_T]): + """A mixin that expects to be mixing in a Query class with + AbstractAppender. + + + """ + + query_class: Optional[Type[Query[_T]]] = None + _order_by_clauses: Tuple[ColumnElement[Any], ...] + + def __init__( + self, attr: DynamicAttributeImpl, state: InstanceState[_T] + ) -> None: + Query.__init__( + self, # type: ignore[arg-type] + attr.target_mapper, + None, + ) + super().__init__(attr, state) + + @property + def session(self) -> Optional[Session]: + sess = object_session(self.instance) + if sess is not None and sess.autoflush and self.instance in sess: + sess.flush() + if not orm_util.has_identity(self.instance): + return None + else: + return sess + + @session.setter + def session(self, session: Session) -> None: + self.sess = session + + def _iter(self) -> Union[result.ScalarResult[_T], result.Result[_T]]: + sess = self.session + if sess is None: + state = attributes.instance_state(self.instance) + if state.detached: + util.warn( + "Instance %s is detached, dynamic relationship cannot " + "return a correct result. This warning will become " + "a DetachedInstanceError in a future release." + % (orm_util.state_str(state)) + ) + + return result.IteratorResult( + result.SimpleResultMetaData([self.attr.class_.__name__]), + iter( + self.attr._get_collection_history( + attributes.instance_state(self.instance), + PassiveFlag.PASSIVE_NO_INITIALIZE, + ).added_items + ), + _source_supports_scalars=True, + ).scalars() + else: + return self._generate(sess)._iter() + + if TYPE_CHECKING: + + def __iter__(self) -> Iterator[_T]: ... + + @overload + def __getitem__(self, index: int) -> _T: ... + + @overload + def __getitem__(self, index: slice) -> List[_T]: ... + + def __getitem__(self, index: Union[int, slice]) -> Union[_T, List[_T]]: + sess = self.session + if sess is None: + return self.attr._get_collection_history( + attributes.instance_state(self.instance), + PassiveFlag.PASSIVE_NO_INITIALIZE, + ).indexed(index) + else: + return self._generate(sess).__getitem__(index) + + def count(self) -> int: + sess = self.session + if sess is None: + return len( + self.attr._get_collection_history( + attributes.instance_state(self.instance), + PassiveFlag.PASSIVE_NO_INITIALIZE, + ).added_items + ) + else: + return self._generate(sess).count() + + def _generate( + self, + sess: Optional[Session] = None, + ) -> Query[_T]: + # note we're returning an entirely new Query class instance + # here without any assignment capabilities; the class of this + # query is determined by the session. + instance = self.instance + if sess is None: + sess = object_session(instance) + if sess is None: + raise orm_exc.DetachedInstanceError( + "Parent instance %s is not bound to a Session, and no " + "contextual session is established; lazy load operation " + "of attribute '%s' cannot proceed" + % (orm_util.instance_str(instance), self.attr.key) + ) + + if self.query_class: + query = self.query_class(self.attr.target_mapper, session=sess) + else: + query = sess.query(self.attr.target_mapper) + + query._where_criteria = self._where_criteria + query._from_obj = self._from_obj + query._order_by_clauses = self._order_by_clauses + + return query + + def add_all(self, iterator: Iterable[_T]) -> None: + """Add an iterable of items to this :class:`_orm.AppenderQuery`. + + The given items will be persisted to the database in terms of + the parent instance's collection on the next flush. + + This method is provided to assist in delivering forwards-compatibility + with the :class:`_orm.WriteOnlyCollection` collection class. + + .. versionadded:: 2.0 + + """ + self._add_all_impl(iterator) + + def add(self, item: _T) -> None: + """Add an item to this :class:`_orm.AppenderQuery`. + + The given item will be persisted to the database in terms of + the parent instance's collection on the next flush. + + This method is provided to assist in delivering forwards-compatibility + with the :class:`_orm.WriteOnlyCollection` collection class. + + .. versionadded:: 2.0 + + """ + self._add_all_impl([item]) + + def extend(self, iterator: Iterable[_T]) -> None: + """Add an iterable of items to this :class:`_orm.AppenderQuery`. + + The given items will be persisted to the database in terms of + the parent instance's collection on the next flush. + + """ + self._add_all_impl(iterator) + + def append(self, item: _T) -> None: + """Append an item to this :class:`_orm.AppenderQuery`. + + The given item will be persisted to the database in terms of + the parent instance's collection on the next flush. + + """ + self._add_all_impl([item]) + + def remove(self, item: _T) -> None: + """Remove an item from this :class:`_orm.AppenderQuery`. + + The given item will be removed from the parent instance's collection on + the next flush. + + """ + self._remove_impl(item) + + +class AppenderQuery(AppenderMixin[_T], Query[_T]): # type: ignore[misc] + """A dynamic query that supports basic collection storage operations. + + Methods on :class:`.AppenderQuery` include all methods of + :class:`_orm.Query`, plus additional methods used for collection + persistence. + + + """ + + +def mixin_user_query(cls: Any) -> type[AppenderMixin[Any]]: + """Return a new class with AppenderQuery functionality layered over.""" + name = "Appender" + cls.__name__ + return type(name, (AppenderMixin, cls), {"query_class": cls}) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/evaluator.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e462c018ceec3172c9cf5b422214c4d05640b3b1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/evaluator.py @@ -0,0 +1,379 @@ +# orm/evaluator.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + +"""Evaluation functions used **INTERNALLY** by ORM DML use cases. + + +This module is **private, for internal use by SQLAlchemy**. + +.. versionchanged:: 2.0.4 renamed ``EvaluatorCompiler`` to + ``_EvaluatorCompiler``. + +""" + + +from __future__ import annotations + +from typing import Type + +from . import exc as orm_exc +from .base import LoaderCallableStatus +from .base import PassiveFlag +from .. import exc +from .. import inspect +from ..sql import and_ +from ..sql import operators +from ..sql.sqltypes import Concatenable +from ..sql.sqltypes import Integer +from ..sql.sqltypes import Numeric +from ..util import warn_deprecated + + +class UnevaluatableError(exc.InvalidRequestError): + pass + + +class _NoObject(operators.ColumnOperators): + def operate(self, *arg, **kw): + return None + + def reverse_operate(self, *arg, **kw): + return None + + +class _ExpiredObject(operators.ColumnOperators): + def operate(self, *arg, **kw): + return self + + def reverse_operate(self, *arg, **kw): + return self + + +_NO_OBJECT = _NoObject() +_EXPIRED_OBJECT = _ExpiredObject() + + +class _EvaluatorCompiler: + def __init__(self, target_cls=None): + self.target_cls = target_cls + + def process(self, clause, *clauses): + if clauses: + clause = and_(clause, *clauses) + + meth = getattr(self, f"visit_{clause.__visit_name__}", None) + if not meth: + raise UnevaluatableError( + f"Cannot evaluate {type(clause).__name__}" + ) + return meth(clause) + + def visit_grouping(self, clause): + return self.process(clause.element) + + def visit_null(self, clause): + return lambda obj: None + + def visit_false(self, clause): + return lambda obj: False + + def visit_true(self, clause): + return lambda obj: True + + def visit_column(self, clause): + try: + parentmapper = clause._annotations["parentmapper"] + except KeyError as ke: + raise UnevaluatableError( + f"Cannot evaluate column: {clause}" + ) from ke + + if self.target_cls and not issubclass( + self.target_cls, parentmapper.class_ + ): + raise UnevaluatableError( + "Can't evaluate criteria against " + f"alternate class {parentmapper.class_}" + ) + + parentmapper._check_configure() + + # we'd like to use "proxy_key" annotation to get the "key", however + # in relationship primaryjoin cases proxy_key is sometimes deannotated + # and sometimes apparently not present in the first place (?). + # While I can stop it from being deannotated (though need to see if + # this breaks other things), not sure right now about cases where it's + # not there in the first place. can fix at some later point. + # key = clause._annotations["proxy_key"] + + # for now, use the old way + try: + key = parentmapper._columntoproperty[clause].key + except orm_exc.UnmappedColumnError as err: + raise UnevaluatableError( + f"Cannot evaluate expression: {err}" + ) from err + + # note this used to fall back to a simple `getattr(obj, key)` evaluator + # if impl was None; as of #8656, we ensure mappers are configured + # so that impl is available + impl = parentmapper.class_manager[key].impl + + def get_corresponding_attr(obj): + if obj is None: + return _NO_OBJECT + state = inspect(obj) + dict_ = state.dict + + value = impl.get( + state, dict_, passive=PassiveFlag.PASSIVE_NO_FETCH + ) + if value is LoaderCallableStatus.PASSIVE_NO_RESULT: + return _EXPIRED_OBJECT + return value + + return get_corresponding_attr + + def visit_tuple(self, clause): + return self.visit_clauselist(clause) + + def visit_expression_clauselist(self, clause): + return self.visit_clauselist(clause) + + def visit_clauselist(self, clause): + evaluators = [self.process(clause) for clause in clause.clauses] + + dispatch = ( + f"visit_{clause.operator.__name__.rstrip('_')}_clauselist_op" + ) + meth = getattr(self, dispatch, None) + if meth: + return meth(clause.operator, evaluators, clause) + else: + raise UnevaluatableError( + f"Cannot evaluate clauselist with operator {clause.operator}" + ) + + def visit_binary(self, clause): + eval_left = self.process(clause.left) + eval_right = self.process(clause.right) + + dispatch = f"visit_{clause.operator.__name__.rstrip('_')}_binary_op" + meth = getattr(self, dispatch, None) + if meth: + return meth(clause.operator, eval_left, eval_right, clause) + else: + raise UnevaluatableError( + f"Cannot evaluate {type(clause).__name__} with " + f"operator {clause.operator}" + ) + + def visit_or_clauselist_op(self, operator, evaluators, clause): + def evaluate(obj): + has_null = False + for sub_evaluate in evaluators: + value = sub_evaluate(obj) + if value is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + elif value: + return True + has_null = has_null or value is None + if has_null: + return None + return False + + return evaluate + + def visit_and_clauselist_op(self, operator, evaluators, clause): + def evaluate(obj): + for sub_evaluate in evaluators: + value = sub_evaluate(obj) + if value is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + + if not value: + if value is None or value is _NO_OBJECT: + return None + return False + return True + + return evaluate + + def visit_comma_op_clauselist_op(self, operator, evaluators, clause): + def evaluate(obj): + values = [] + for sub_evaluate in evaluators: + value = sub_evaluate(obj) + if value is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + elif value is None or value is _NO_OBJECT: + return None + values.append(value) + return tuple(values) + + return evaluate + + def visit_custom_op_binary_op( + self, operator, eval_left, eval_right, clause + ): + if operator.python_impl: + return self._straight_evaluate( + operator, eval_left, eval_right, clause + ) + else: + raise UnevaluatableError( + f"Custom operator {operator.opstring!r} can't be evaluated " + "in Python unless it specifies a callable using " + "`.python_impl`." + ) + + def visit_is_binary_op(self, operator, eval_left, eval_right, clause): + def evaluate(obj): + left_val = eval_left(obj) + right_val = eval_right(obj) + if left_val is _EXPIRED_OBJECT or right_val is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + return left_val == right_val + + return evaluate + + def visit_is_not_binary_op(self, operator, eval_left, eval_right, clause): + def evaluate(obj): + left_val = eval_left(obj) + right_val = eval_right(obj) + if left_val is _EXPIRED_OBJECT or right_val is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + return left_val != right_val + + return evaluate + + def _straight_evaluate(self, operator, eval_left, eval_right, clause): + def evaluate(obj): + left_val = eval_left(obj) + right_val = eval_right(obj) + if left_val is _EXPIRED_OBJECT or right_val is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + elif left_val is None or right_val is None: + return None + + return operator(eval_left(obj), eval_right(obj)) + + return evaluate + + def _straight_evaluate_numeric_only( + self, operator, eval_left, eval_right, clause + ): + if clause.left.type._type_affinity not in ( + Numeric, + Integer, + ) or clause.right.type._type_affinity not in (Numeric, Integer): + raise UnevaluatableError( + f'Cannot evaluate math operator "{operator.__name__}" for ' + f"datatypes {clause.left.type}, {clause.right.type}" + ) + + return self._straight_evaluate(operator, eval_left, eval_right, clause) + + visit_add_binary_op = _straight_evaluate_numeric_only + visit_mul_binary_op = _straight_evaluate_numeric_only + visit_sub_binary_op = _straight_evaluate_numeric_only + visit_mod_binary_op = _straight_evaluate_numeric_only + visit_truediv_binary_op = _straight_evaluate_numeric_only + visit_lt_binary_op = _straight_evaluate + visit_le_binary_op = _straight_evaluate + visit_ne_binary_op = _straight_evaluate + visit_gt_binary_op = _straight_evaluate + visit_ge_binary_op = _straight_evaluate + visit_eq_binary_op = _straight_evaluate + + def visit_in_op_binary_op(self, operator, eval_left, eval_right, clause): + return self._straight_evaluate( + lambda a, b: a in b if a is not _NO_OBJECT else None, + eval_left, + eval_right, + clause, + ) + + def visit_not_in_op_binary_op( + self, operator, eval_left, eval_right, clause + ): + return self._straight_evaluate( + lambda a, b: a not in b if a is not _NO_OBJECT else None, + eval_left, + eval_right, + clause, + ) + + def visit_concat_op_binary_op( + self, operator, eval_left, eval_right, clause + ): + + if not issubclass( + clause.left.type._type_affinity, Concatenable + ) or not issubclass(clause.right.type._type_affinity, Concatenable): + raise UnevaluatableError( + f"Cannot evaluate concatenate operator " + f'"{operator.__name__}" for ' + f"datatypes {clause.left.type}, {clause.right.type}" + ) + + return self._straight_evaluate( + lambda a, b: a + b, eval_left, eval_right, clause + ) + + def visit_startswith_op_binary_op( + self, operator, eval_left, eval_right, clause + ): + return self._straight_evaluate( + lambda a, b: a.startswith(b), eval_left, eval_right, clause + ) + + def visit_endswith_op_binary_op( + self, operator, eval_left, eval_right, clause + ): + return self._straight_evaluate( + lambda a, b: a.endswith(b), eval_left, eval_right, clause + ) + + def visit_unary(self, clause): + eval_inner = self.process(clause.element) + if clause.operator is operators.inv: + + def evaluate(obj): + value = eval_inner(obj) + if value is _EXPIRED_OBJECT: + return _EXPIRED_OBJECT + elif value is None: + return None + return not value + + return evaluate + raise UnevaluatableError( + f"Cannot evaluate {type(clause).__name__} " + f"with operator {clause.operator}" + ) + + def visit_bindparam(self, clause): + if clause.callable: + val = clause.callable() + else: + val = clause.value + return lambda obj: val + + +def __getattr__(name: str) -> Type[_EvaluatorCompiler]: + if name == "EvaluatorCompiler": + warn_deprecated( + "Direct use of 'EvaluatorCompiler' is not supported, and this " + "name will be removed in a future release. " + "'_EvaluatorCompiler' is for internal use only", + "2.0", + ) + return _EvaluatorCompiler + else: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/events.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/events.py new file mode 100644 index 0000000000000000000000000000000000000000..59e04071878977acf90f6b3081d430c12961c64e --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/events.py @@ -0,0 +1,3252 @@ +# orm/events.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""ORM event interfaces.""" +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import Collection +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import instrumentation +from . import interfaces +from . import mapperlib +from .attributes import QueryableAttribute +from .base import _mapper_or_none +from .base import NO_KEY +from .instrumentation import ClassManager +from .instrumentation import InstrumentationFactory +from .query import BulkDelete +from .query import BulkUpdate +from .query import Query +from .scoping import scoped_session +from .session import Session +from .session import sessionmaker +from .. import event +from .. import exc +from .. import util +from ..event import EventTarget +from ..event.registry import _ET +from ..util.compat import inspect_getfullargspec + +if TYPE_CHECKING: + from weakref import ReferenceType + + from ._typing import _InstanceDict + from ._typing import _InternalEntityType + from ._typing import _O + from ._typing import _T + from .attributes import Event + from .base import EventConstants + from .session import ORMExecuteState + from .session import SessionTransaction + from .unitofwork import UOWTransaction + from ..engine import Connection + from ..event.base import _Dispatch + from ..event.base import _HasEventsDispatch + from ..event.registry import _EventKey + from ..orm.collections import CollectionAdapter + from ..orm.context import QueryContext + from ..orm.decl_api import DeclarativeAttributeIntercept + from ..orm.decl_api import DeclarativeMeta + from ..orm.mapper import Mapper + from ..orm.state import InstanceState + +_KT = TypeVar("_KT", bound=Any) +_ET2 = TypeVar("_ET2", bound=EventTarget) + + +class InstrumentationEvents(event.Events[InstrumentationFactory]): + """Events related to class instrumentation events. + + The listeners here support being established against + any new style class, that is any object that is a subclass + of 'type'. Events will then be fired off for events + against that class. If the "propagate=True" flag is passed + to event.listen(), the event will fire off for subclasses + of that class as well. + + The Python ``type`` builtin is also accepted as a target, + which when used has the effect of events being emitted + for all classes. + + Note the "propagate" flag here is defaulted to ``True``, + unlike the other class level events where it defaults + to ``False``. This means that new subclasses will also + be the subject of these events, when a listener + is established on a superclass. + + """ + + _target_class_doc = "SomeBaseClass" + _dispatch_target = InstrumentationFactory + + @classmethod + def _accept_with( + cls, + target: Union[ + InstrumentationFactory, + Type[InstrumentationFactory], + ], + identifier: str, + ) -> Optional[ + Union[ + InstrumentationFactory, + Type[InstrumentationFactory], + ] + ]: + if isinstance(target, type): + return _InstrumentationEventsHold(target) # type: ignore [return-value] # noqa: E501 + else: + return None + + @classmethod + def _listen( + cls, event_key: _EventKey[_T], propagate: bool = True, **kw: Any + ) -> None: + target, identifier, fn = ( + event_key.dispatch_target, + event_key.identifier, + event_key._listen_fn, + ) + + def listen(target_cls: type, *arg: Any) -> Optional[Any]: + listen_cls = target() + + # if weakref were collected, however this is not something + # that normally happens. it was occurring during test teardown + # between mapper/registry/instrumentation_manager, however this + # interaction was changed to not rely upon the event system. + if listen_cls is None: + return None + + if propagate and issubclass(target_cls, listen_cls): + return fn(target_cls, *arg) + elif not propagate and target_cls is listen_cls: + return fn(target_cls, *arg) + else: + return None + + def remove(ref: ReferenceType[_T]) -> None: + key = event.registry._EventKey( # type: ignore [type-var] + None, + identifier, + listen, + instrumentation._instrumentation_factory, + ) + getattr( + instrumentation._instrumentation_factory.dispatch, identifier + ).remove(key) + + target = weakref.ref(target.class_, remove) + + event_key.with_dispatch_target( + instrumentation._instrumentation_factory + ).with_wrapper(listen).base_listen(**kw) + + @classmethod + def _clear(cls) -> None: + super()._clear() + instrumentation._instrumentation_factory.dispatch._clear() + + def class_instrument(self, cls: ClassManager[_O]) -> None: + """Called after the given class is instrumented. + + To get at the :class:`.ClassManager`, use + :func:`.manager_of_class`. + + """ + + def class_uninstrument(self, cls: ClassManager[_O]) -> None: + """Called before the given class is uninstrumented. + + To get at the :class:`.ClassManager`, use + :func:`.manager_of_class`. + + """ + + def attribute_instrument( + self, cls: ClassManager[_O], key: _KT, inst: _O + ) -> None: + """Called when an attribute is instrumented.""" + + +class _InstrumentationEventsHold: + """temporary marker object used to transfer from _accept_with() to + _listen() on the InstrumentationEvents class. + + """ + + def __init__(self, class_: type) -> None: + self.class_ = class_ + + dispatch = event.dispatcher(InstrumentationEvents) + + +class InstanceEvents(event.Events[ClassManager[Any]]): + """Define events specific to object lifecycle. + + e.g.:: + + from sqlalchemy import event + + + def my_load_listener(target, context): + print("on load!") + + + event.listen(SomeClass, "load", my_load_listener) + + Available targets include: + + * mapped classes + * unmapped superclasses of mapped or to-be-mapped classes + (using the ``propagate=True`` flag) + * :class:`_orm.Mapper` objects + * the :class:`_orm.Mapper` class itself indicates listening for all + mappers. + + Instance events are closely related to mapper events, but + are more specific to the instance and its instrumentation, + rather than its system of persistence. + + When using :class:`.InstanceEvents`, several modifiers are + available to the :func:`.event.listen` function. + + :param propagate=False: When True, the event listener should + be applied to all inheriting classes as well as the + class which is the target of this listener. + :param raw=False: When True, the "target" argument passed + to applicable event listener functions will be the + instance's :class:`.InstanceState` management + object, rather than the mapped instance itself. + :param restore_load_context=False: Applies to the + :meth:`.InstanceEvents.load` and :meth:`.InstanceEvents.refresh` + events. Restores the loader context of the object when the event + hook is complete, so that ongoing eager load operations continue + to target the object appropriately. A warning is emitted if the + object is moved to a new loader context from within one of these + events if this flag is not set. + + .. versionadded:: 1.3.14 + + + """ + + _target_class_doc = "SomeClass" + + _dispatch_target = ClassManager + + @classmethod + def _new_classmanager_instance( + cls, + class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type], + classmanager: ClassManager[_O], + ) -> None: + _InstanceEventsHold.populate(class_, classmanager) + + @classmethod + @util.preload_module("sqlalchemy.orm") + def _accept_with( + cls, + target: Union[ + ClassManager[Any], + Type[ClassManager[Any]], + ], + identifier: str, + ) -> Optional[Union[ClassManager[Any], Type[ClassManager[Any]]]]: + orm = util.preloaded.orm + + if isinstance(target, ClassManager): + return target + elif isinstance(target, mapperlib.Mapper): + return target.class_manager + elif target is orm.mapper: # type: ignore [attr-defined] + util.warn_deprecated( + "The `sqlalchemy.orm.mapper()` symbol is deprecated and " + "will be removed in a future release. For the mapper-wide " + "event target, use the 'sqlalchemy.orm.Mapper' class.", + "2.0", + ) + return ClassManager + elif isinstance(target, type): + if issubclass(target, mapperlib.Mapper): + return ClassManager + else: + manager = instrumentation.opt_manager_of_class(target) + if manager: + return manager + else: + return _InstanceEventsHold(target) # type: ignore [return-value] # noqa: E501 + return None + + @classmethod + def _listen( + cls, + event_key: _EventKey[ClassManager[Any]], + raw: bool = False, + propagate: bool = False, + restore_load_context: bool = False, + **kw: Any, + ) -> None: + target, fn = (event_key.dispatch_target, event_key._listen_fn) + + if not raw or restore_load_context: + + def wrap( + state: InstanceState[_O], *arg: Any, **kw: Any + ) -> Optional[Any]: + if not raw: + target: Any = state.obj() + else: + target = state + if restore_load_context: + runid = state.runid + try: + return fn(target, *arg, **kw) + finally: + if restore_load_context: + state.runid = runid + + event_key = event_key.with_wrapper(wrap) + + event_key.base_listen(propagate=propagate, **kw) + + if propagate: + for mgr in target.subclass_managers(True): + event_key.with_dispatch_target(mgr).base_listen(propagate=True) + + @classmethod + def _clear(cls) -> None: + super()._clear() + _InstanceEventsHold._clear() + + def first_init(self, manager: ClassManager[_O], cls: Type[_O]) -> None: + """Called when the first instance of a particular mapping is called. + + This event is called when the ``__init__`` method of a class + is called the first time for that particular class. The event + invokes before ``__init__`` actually proceeds as well as before + the :meth:`.InstanceEvents.init` event is invoked. + + """ + + def init(self, target: _O, args: Any, kwargs: Any) -> None: + """Receive an instance when its constructor is called. + + This method is only called during a userland construction of + an object, in conjunction with the object's constructor, e.g. + its ``__init__`` method. It is not called when an object is + loaded from the database; see the :meth:`.InstanceEvents.load` + event in order to intercept a database load. + + The event is called before the actual ``__init__`` constructor + of the object is called. The ``kwargs`` dictionary may be + modified in-place in order to affect what is passed to + ``__init__``. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param args: positional arguments passed to the ``__init__`` method. + This is passed as a tuple and is currently immutable. + :param kwargs: keyword arguments passed to the ``__init__`` method. + This structure *can* be altered in place. + + .. seealso:: + + :meth:`.InstanceEvents.init_failure` + + :meth:`.InstanceEvents.load` + + """ + + def init_failure(self, target: _O, args: Any, kwargs: Any) -> None: + """Receive an instance when its constructor has been called, + and raised an exception. + + This method is only called during a userland construction of + an object, in conjunction with the object's constructor, e.g. + its ``__init__`` method. It is not called when an object is loaded + from the database. + + The event is invoked after an exception raised by the ``__init__`` + method is caught. After the event + is invoked, the original exception is re-raised outwards, so that + the construction of the object still raises an exception. The + actual exception and stack trace raised should be present in + ``sys.exc_info()``. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param args: positional arguments that were passed to the ``__init__`` + method. + :param kwargs: keyword arguments that were passed to the ``__init__`` + method. + + .. seealso:: + + :meth:`.InstanceEvents.init` + + :meth:`.InstanceEvents.load` + + """ + + def _sa_event_merge_wo_load( + self, target: _O, context: QueryContext + ) -> None: + """receive an object instance after it was the subject of a merge() + call, when load=False was passed. + + The target would be the already-loaded object in the Session which + would have had its attributes overwritten by the incoming object. This + overwrite operation does not use attribute events, instead just + populating dict directly. Therefore the purpose of this event is so + that extensions like sqlalchemy.ext.mutable know that object state has + changed and incoming state needs to be set up for "parents" etc. + + This functionality is acceptable to be made public in a later release. + + .. versionadded:: 1.4.41 + + """ + + def load(self, target: _O, context: QueryContext) -> None: + """Receive an object instance after it has been created via + ``__new__``, and after initial attribute population has + occurred. + + This typically occurs when the instance is created based on + incoming result rows, and is only called once for that + instance's lifetime. + + .. warning:: + + During a result-row load, this event is invoked when the + first row received for this instance is processed. When using + eager loading with collection-oriented attributes, the additional + rows that are to be loaded / processed in order to load subsequent + collection items have not occurred yet. This has the effect + both that collections will not be fully loaded, as well as that + if an operation occurs within this event handler that emits + another database load operation for the object, the "loading + context" for the object can change and interfere with the + existing eager loaders still in progress. + + Examples of what can cause the "loading context" to change within + the event handler include, but are not necessarily limited to: + + * accessing deferred attributes that weren't part of the row, + will trigger an "undefer" operation and refresh the object + + * accessing attributes on a joined-inheritance subclass that + weren't part of the row, will trigger a refresh operation. + + As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The + :paramref:`.InstanceEvents.restore_load_context` option may be + used on the event to prevent this warning; this will ensure that + the existing loading context is maintained for the object after the + event is called:: + + @event.listens_for(SomeClass, "load", restore_load_context=True) + def on_load(instance, context): + instance.some_unloaded_attribute + + .. versionchanged:: 1.3.14 Added + :paramref:`.InstanceEvents.restore_load_context` + and :paramref:`.SessionEvents.restore_load_context` flags which + apply to "on load" events, which will ensure that the loading + context for an object is restored when the event hook is + complete; a warning is emitted if the load context of the object + changes without this flag being set. + + + The :meth:`.InstanceEvents.load` event is also available in a + class-method decorator format called :func:`_orm.reconstructor`. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param context: the :class:`.QueryContext` corresponding to the + current :class:`_query.Query` in progress. This argument may be + ``None`` if the load does not correspond to a :class:`_query.Query`, + such as during :meth:`.Session.merge`. + + .. seealso:: + + :ref:`mapped_class_load_events` + + :meth:`.InstanceEvents.init` + + :meth:`.InstanceEvents.refresh` + + :meth:`.SessionEvents.loaded_as_persistent` + + """ # noqa: E501 + + def refresh( + self, target: _O, context: QueryContext, attrs: Optional[Iterable[str]] + ) -> None: + """Receive an object instance after one or more attributes have + been refreshed from a query. + + Contrast this to the :meth:`.InstanceEvents.load` method, which + is invoked when the object is first loaded from a query. + + .. note:: This event is invoked within the loader process before + eager loaders may have been completed, and the object's state may + not be complete. Additionally, invoking row-level refresh + operations on the object will place the object into a new loader + context, interfering with the existing load context. See the note + on :meth:`.InstanceEvents.load` for background on making use of the + :paramref:`.InstanceEvents.restore_load_context` parameter, in + order to resolve this scenario. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param context: the :class:`.QueryContext` corresponding to the + current :class:`_query.Query` in progress. + :param attrs: sequence of attribute names which + were populated, or None if all column-mapped, non-deferred + attributes were populated. + + .. seealso:: + + :ref:`mapped_class_load_events` + + :meth:`.InstanceEvents.load` + + """ + + def refresh_flush( + self, + target: _O, + flush_context: UOWTransaction, + attrs: Optional[Iterable[str]], + ) -> None: + """Receive an object instance after one or more attributes that + contain a column-level default or onupdate handler have been refreshed + during persistence of the object's state. + + This event is the same as :meth:`.InstanceEvents.refresh` except + it is invoked within the unit of work flush process, and includes + only non-primary-key columns that have column level default or + onupdate handlers, including Python callables as well as server side + defaults and triggers which may be fetched via the RETURNING clause. + + .. note:: + + While the :meth:`.InstanceEvents.refresh_flush` event is triggered + for an object that was INSERTed as well as for an object that was + UPDATEd, the event is geared primarily towards the UPDATE process; + it is mostly an internal artifact that INSERT actions can also + trigger this event, and note that **primary key columns for an + INSERTed row are explicitly omitted** from this event. In order to + intercept the newly INSERTed state of an object, the + :meth:`.SessionEvents.pending_to_persistent` and + :meth:`.MapperEvents.after_insert` are better choices. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param flush_context: Internal :class:`.UOWTransaction` object + which handles the details of the flush. + :param attrs: sequence of attribute names which + were populated. + + .. seealso:: + + :ref:`mapped_class_load_events` + + :ref:`orm_server_defaults` + + :ref:`metadata_defaults_toplevel` + + """ + + def expire(self, target: _O, attrs: Optional[Iterable[str]]) -> None: + """Receive an object instance after its attributes or some subset + have been expired. + + 'keys' is a list of attribute names. If None, the entire + state was expired. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param attrs: sequence of attribute + names which were expired, or None if all attributes were + expired. + + """ + + def pickle(self, target: _O, state_dict: _InstanceDict) -> None: + """Receive an object instance when its associated state is + being pickled. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param state_dict: the dictionary returned by + :class:`.InstanceState.__getstate__`, containing the state + to be pickled. + + """ + + def unpickle(self, target: _O, state_dict: _InstanceDict) -> None: + """Receive an object instance after its associated state has + been unpickled. + + :param target: the mapped instance. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :param state_dict: the dictionary sent to + :class:`.InstanceState.__setstate__`, containing the state + dictionary which was pickled. + + """ + + +class _EventsHold(event.RefCollection[_ET]): + """Hold onto listeners against unmapped, uninstrumented classes. + + Establish _listen() for that class' mapper/instrumentation when + those objects are created for that class. + + """ + + all_holds: weakref.WeakKeyDictionary[Any, Any] + + def __init__( + self, + class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type], + ) -> None: + self.class_ = class_ + + @classmethod + def _clear(cls) -> None: + cls.all_holds.clear() + + class HoldEvents(Generic[_ET2]): + _dispatch_target: Optional[Type[_ET2]] = None + + @classmethod + def _listen( + cls, + event_key: _EventKey[_ET2], + raw: bool = False, + propagate: bool = False, + retval: bool = False, + **kw: Any, + ) -> None: + target = event_key.dispatch_target + + if target.class_ in target.all_holds: + collection = target.all_holds[target.class_] + else: + collection = target.all_holds[target.class_] = {} + + event.registry._stored_in_collection(event_key, target) + collection[event_key._key] = ( + event_key, + raw, + propagate, + retval, + kw, + ) + + if propagate: + stack = list(target.class_.__subclasses__()) + while stack: + subclass = stack.pop(0) + stack.extend(subclass.__subclasses__()) + subject = target.resolve(subclass) + if subject is not None: + # we are already going through __subclasses__() + # so leave generic propagate flag False + event_key.with_dispatch_target(subject).listen( + raw=raw, propagate=False, retval=retval, **kw + ) + + def remove(self, event_key: _EventKey[_ET]) -> None: + target = event_key.dispatch_target + + if isinstance(target, _EventsHold): + collection = target.all_holds[target.class_] + del collection[event_key._key] + + @classmethod + def populate( + cls, + class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type], + subject: Union[ClassManager[_O], Mapper[_O]], + ) -> None: + for subclass in class_.__mro__: + if subclass in cls.all_holds: + collection = cls.all_holds[subclass] + for ( + event_key, + raw, + propagate, + retval, + kw, + ) in collection.values(): + if propagate or subclass is class_: + # since we can't be sure in what order different + # classes in a hierarchy are triggered with + # populate(), we rely upon _EventsHold for all event + # assignment, instead of using the generic propagate + # flag. + event_key.with_dispatch_target(subject).listen( + raw=raw, propagate=False, retval=retval, **kw + ) + + +class _InstanceEventsHold(_EventsHold[_ET]): + all_holds: weakref.WeakKeyDictionary[Any, Any] = ( + weakref.WeakKeyDictionary() + ) + + def resolve(self, class_: Type[_O]) -> Optional[ClassManager[_O]]: + return instrumentation.opt_manager_of_class(class_) + + # this fails on pyright if you use Any. Fails on mypy if you use _ET + class HoldInstanceEvents(_EventsHold.HoldEvents[_ET], InstanceEvents): # type: ignore[valid-type,misc] # noqa: E501 + pass + + dispatch = event.dispatcher(HoldInstanceEvents) + + +class MapperEvents(event.Events[mapperlib.Mapper[Any]]): + """Define events specific to mappings. + + e.g.:: + + from sqlalchemy import event + + + def my_before_insert_listener(mapper, connection, target): + # execute a stored procedure upon INSERT, + # apply the value to the row to be inserted + target.calculated_value = connection.execute( + text("select my_special_function(%d)" % target.special_number) + ).scalar() + + + # associate the listener function with SomeClass, + # to execute during the "before_insert" hook + event.listen(SomeClass, "before_insert", my_before_insert_listener) + + Available targets include: + + * mapped classes + * unmapped superclasses of mapped or to-be-mapped classes + (using the ``propagate=True`` flag) + * :class:`_orm.Mapper` objects + * the :class:`_orm.Mapper` class itself indicates listening for all + mappers. + + Mapper events provide hooks into critical sections of the + mapper, including those related to object instrumentation, + object loading, and object persistence. In particular, the + persistence methods :meth:`~.MapperEvents.before_insert`, + and :meth:`~.MapperEvents.before_update` are popular + places to augment the state being persisted - however, these + methods operate with several significant restrictions. The + user is encouraged to evaluate the + :meth:`.SessionEvents.before_flush` and + :meth:`.SessionEvents.after_flush` methods as more + flexible and user-friendly hooks in which to apply + additional database state during a flush. + + When using :class:`.MapperEvents`, several modifiers are + available to the :func:`.event.listen` function. + + :param propagate=False: When True, the event listener should + be applied to all inheriting mappers and/or the mappers of + inheriting classes, as well as any + mapper which is the target of this listener. + :param raw=False: When True, the "target" argument passed + to applicable event listener functions will be the + instance's :class:`.InstanceState` management + object, rather than the mapped instance itself. + :param retval=False: when True, the user-defined event function + must have a return value, the purpose of which is either to + control subsequent event propagation, or to otherwise alter + the operation in progress by the mapper. Possible return + values are: + + * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event + processing normally. + * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent + event handlers in the chain. + * other values - the return value specified by specific listeners. + + """ + + _target_class_doc = "SomeClass" + _dispatch_target = mapperlib.Mapper + + @classmethod + def _new_mapper_instance( + cls, + class_: Union[DeclarativeAttributeIntercept, DeclarativeMeta, type], + mapper: Mapper[_O], + ) -> None: + _MapperEventsHold.populate(class_, mapper) + + @classmethod + @util.preload_module("sqlalchemy.orm") + def _accept_with( + cls, + target: Union[mapperlib.Mapper[Any], Type[mapperlib.Mapper[Any]]], + identifier: str, + ) -> Optional[Union[mapperlib.Mapper[Any], Type[mapperlib.Mapper[Any]]]]: + orm = util.preloaded.orm + + if target is orm.mapper: # type: ignore [attr-defined] + util.warn_deprecated( + "The `sqlalchemy.orm.mapper()` symbol is deprecated and " + "will be removed in a future release. For the mapper-wide " + "event target, use the 'sqlalchemy.orm.Mapper' class.", + "2.0", + ) + return mapperlib.Mapper + elif isinstance(target, type): + if issubclass(target, mapperlib.Mapper): + return target + else: + mapper = _mapper_or_none(target) + if mapper is not None: + return mapper + else: + return _MapperEventsHold(target) + else: + return target + + @classmethod + def _listen( + cls, + event_key: _EventKey[_ET], + raw: bool = False, + retval: bool = False, + propagate: bool = False, + **kw: Any, + ) -> None: + target, identifier, fn = ( + event_key.dispatch_target, + event_key.identifier, + event_key._listen_fn, + ) + + if ( + identifier in ("before_configured", "after_configured") + and target is not mapperlib.Mapper + ): + util.warn( + "'before_configured' and 'after_configured' ORM events " + "only invoke with the Mapper class " + "as the target." + ) + + if not raw or not retval: + if not raw: + meth = getattr(cls, identifier) + try: + target_index = ( + inspect_getfullargspec(meth)[0].index("target") - 1 + ) + except ValueError: + target_index = None + + def wrap(*arg: Any, **kw: Any) -> Any: + if not raw and target_index is not None: + arg = list(arg) # type: ignore [assignment] + arg[target_index] = arg[target_index].obj() # type: ignore [index] # noqa: E501 + if not retval: + fn(*arg, **kw) + return interfaces.EXT_CONTINUE + else: + return fn(*arg, **kw) + + event_key = event_key.with_wrapper(wrap) + + if propagate: + for mapper in target.self_and_descendants: + event_key.with_dispatch_target(mapper).base_listen( + propagate=True, **kw + ) + else: + event_key.base_listen(**kw) + + @classmethod + def _clear(cls) -> None: + super()._clear() + _MapperEventsHold._clear() + + def instrument_class(self, mapper: Mapper[_O], class_: Type[_O]) -> None: + r"""Receive a class when the mapper is first constructed, + before instrumentation is applied to the mapped class. + + This event is the earliest phase of mapper construction. + Most attributes of the mapper are not yet initialized. To + receive an event within initial mapper construction where basic + state is available such as the :attr:`_orm.Mapper.attrs` collection, + the :meth:`_orm.MapperEvents.after_mapper_constructed` event may + be a better choice. + + This listener can either be applied to the :class:`_orm.Mapper` + class overall, or to any un-mapped class which serves as a base + for classes that will be mapped (using the ``propagate=True`` flag):: + + Base = declarative_base() + + + @event.listens_for(Base, "instrument_class", propagate=True) + def on_new_class(mapper, cls_): + "..." + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param class\_: the mapped class. + + .. seealso:: + + :meth:`_orm.MapperEvents.after_mapper_constructed` + + """ + + def after_mapper_constructed( + self, mapper: Mapper[_O], class_: Type[_O] + ) -> None: + """Receive a class and mapper when the :class:`_orm.Mapper` has been + fully constructed. + + This event is called after the initial constructor for + :class:`_orm.Mapper` completes. This occurs after the + :meth:`_orm.MapperEvents.instrument_class` event and after the + :class:`_orm.Mapper` has done an initial pass of its arguments + to generate its collection of :class:`_orm.MapperProperty` objects, + which are accessible via the :meth:`_orm.Mapper.get_property` + method and the :attr:`_orm.Mapper.iterate_properties` attribute. + + This event differs from the + :meth:`_orm.MapperEvents.before_mapper_configured` event in that it + is invoked within the constructor for :class:`_orm.Mapper`, rather + than within the :meth:`_orm.registry.configure` process. Currently, + this event is the only one which is appropriate for handlers that + wish to create additional mapped classes in response to the + construction of this :class:`_orm.Mapper`, which will be part of the + same configure step when :meth:`_orm.registry.configure` next runs. + + .. versionadded:: 2.0.2 + + .. seealso:: + + :ref:`examples_versioning` - an example which illustrates the use + of the :meth:`_orm.MapperEvents.before_mapper_configured` + event to create new mappers to record change-audit histories on + objects. + + """ + + @event._omit_standard_example + def before_mapper_configured( + self, mapper: Mapper[_O], class_: Type[_O] + ) -> None: + """Called right before a specific mapper is to be configured. + + The :meth:`.MapperEvents.before_mapper_configured` event is invoked + for each mapper that is encountered when the + :func:`_orm.configure_mappers` function proceeds through the current + list of not-yet-configured mappers. It is similar to the + :meth:`.MapperEvents.mapper_configured` event, except that it's invoked + right before the configuration occurs, rather than afterwards. + + The :meth:`.MapperEvents.before_mapper_configured` event includes + the special capability where it can force the configure step for a + specific mapper to be skipped; to use this feature, establish + the event using the ``retval=True`` parameter and return + the :attr:`.orm.interfaces.EXT_SKIP` symbol to indicate the mapper + should be left unconfigured:: + + from sqlalchemy import event + from sqlalchemy.orm import EXT_SKIP + from sqlalchemy.orm import DeclarativeBase + + + class DontConfigureBase(DeclarativeBase): + pass + + + @event.listens_for( + DontConfigureBase, + "before_mapper_configured", + # support return values for the event + retval=True, + # propagate the listener to all subclasses of + # DontConfigureBase + propagate=True, + ) + def dont_configure(mapper, cls): + return EXT_SKIP + + .. seealso:: + + :meth:`.MapperEvents.before_configured` + + :meth:`.MapperEvents.after_configured` + + :meth:`.MapperEvents.mapper_configured` + + """ + + def mapper_configured(self, mapper: Mapper[_O], class_: Type[_O]) -> None: + r"""Called when a specific mapper has completed its own configuration + within the scope of the :func:`.configure_mappers` call. + + The :meth:`.MapperEvents.mapper_configured` event is invoked + for each mapper that is encountered when the + :func:`_orm.configure_mappers` function proceeds through the current + list of not-yet-configured mappers. + :func:`_orm.configure_mappers` is typically invoked + automatically as mappings are first used, as well as each time + new mappers have been made available and new mapper use is + detected. + + When the event is called, the mapper should be in its final + state, but **not including backrefs** that may be invoked from + other mappers; they might still be pending within the + configuration operation. Bidirectional relationships that + are instead configured via the + :paramref:`.orm.relationship.back_populates` argument + *will* be fully available, since this style of relationship does not + rely upon other possibly-not-configured mappers to know that they + exist. + + For an event that is guaranteed to have **all** mappers ready + to go including backrefs that are defined only on other + mappings, use the :meth:`.MapperEvents.after_configured` + event; this event invokes only after all known mappings have been + fully configured. + + The :meth:`.MapperEvents.mapper_configured` event, unlike the + :meth:`.MapperEvents.before_configured` or + :meth:`.MapperEvents.after_configured` events, is called for each + mapper/class individually, and the mapper is passed to the event + itself. It also is called exactly once for a particular mapper. The + event is therefore useful for configurational steps that benefit from + being invoked just once on a specific mapper basis, which don't require + that "backref" configurations are necessarily ready yet. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param class\_: the mapped class. + + .. seealso:: + + :meth:`.MapperEvents.before_configured` + + :meth:`.MapperEvents.after_configured` + + :meth:`.MapperEvents.before_mapper_configured` + + """ + # TODO: need coverage for this event + + @event._omit_standard_example + def before_configured(self) -> None: + """Called before a series of mappers have been configured. + + The :meth:`.MapperEvents.before_configured` event is invoked + each time the :func:`_orm.configure_mappers` function is + invoked, before the function has done any of its work. + :func:`_orm.configure_mappers` is typically invoked + automatically as mappings are first used, as well as each time + new mappers have been made available and new mapper use is + detected. + + Similar events to this one include + :meth:`.MapperEvents.after_configured`, which is invoked after a series + of mappers has been configured, as well as + :meth:`.MapperEvents.before_mapper_configured` and + :meth:`.MapperEvents.mapper_configured`, which are both invoked on a + per-mapper basis. + + This event can **only** be applied to the :class:`_orm.Mapper` class, + and not to individual mappings or mapped classes:: + + from sqlalchemy.orm import Mapper + + + @event.listens_for(Mapper, "before_configured") + def go(): ... + + Typically, this event is called once per application, but in practice + may be called more than once, any time new mappers are to be affected + by a :func:`_orm.configure_mappers` call. If new mappings are + constructed after existing ones have already been used, this event will + likely be called again. + + .. seealso:: + + :meth:`.MapperEvents.before_mapper_configured` + + :meth:`.MapperEvents.mapper_configured` + + :meth:`.MapperEvents.after_configured` + + """ + + @event._omit_standard_example + def after_configured(self) -> None: + """Called after a series of mappers have been configured. + + The :meth:`.MapperEvents.after_configured` event is invoked + each time the :func:`_orm.configure_mappers` function is + invoked, after the function has completed its work. + :func:`_orm.configure_mappers` is typically invoked + automatically as mappings are first used, as well as each time + new mappers have been made available and new mapper use is + detected. + + Similar events to this one include + :meth:`.MapperEvents.before_configured`, which is invoked before a + series of mappers are configured, as well as + :meth:`.MapperEvents.before_mapper_configured` and + :meth:`.MapperEvents.mapper_configured`, which are both invoked on a + per-mapper basis. + + This event can **only** be applied to the :class:`_orm.Mapper` class, + and not to individual mappings or mapped classes:: + + from sqlalchemy.orm import Mapper + + + @event.listens_for(Mapper, "after_configured") + def go(): ... + + Typically, this event is called once per application, but in practice + may be called more than once, any time new mappers are to be affected + by a :func:`_orm.configure_mappers` call. If new mappings are + constructed after existing ones have already been used, this event will + likely be called again. + + .. seealso:: + + :meth:`.MapperEvents.before_mapper_configured` + + :meth:`.MapperEvents.mapper_configured` + + :meth:`.MapperEvents.before_configured` + + """ + + def before_insert( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance before an INSERT statement + is emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to modify local, non-object related + attributes on the instance before an INSERT occurs, as well + as to emit additional SQL statements on the given + connection. + + The event is often called for a batch of objects of the + same class before their INSERT statements are emitted at + once in a later step. In the extremely rare case that + this is not desirable, the :class:`_orm.Mapper` object can be + configured with ``batch=False``, which will cause + batches of instances to be broken up into individual + (and more poorly performing) event->persist->event + steps. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit INSERT statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being persisted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + def after_insert( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance after an INSERT statement + is emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to modify in-Python-only + state on the instance after an INSERT occurs, as well + as to emit additional SQL statements on the given + connection. + + The event is often called for a batch of objects of the + same class after their INSERT statements have been + emitted at once in a previous step. In the extremely + rare case that this is not desirable, the + :class:`_orm.Mapper` object can be configured with ``batch=False``, + which will cause batches of instances to be broken up + into individual (and more poorly performing) + event->persist->event steps. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit INSERT statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being persisted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + def before_update( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance before an UPDATE statement + is emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to modify local, non-object related + attributes on the instance before an UPDATE occurs, as well + as to emit additional SQL statements on the given + connection. + + This method is called for all instances that are + marked as "dirty", *even those which have no net changes + to their column-based attributes*. An object is marked + as dirty when any of its column-based attributes have a + "set attribute" operation called or when any of its + collections are modified. If, at update time, no + column-based attributes have any net changes, no UPDATE + statement will be issued. This means that an instance + being sent to :meth:`~.MapperEvents.before_update` is + *not* a guarantee that an UPDATE statement will be + issued, although you can affect the outcome here by + modifying attributes so that a net change in value does + exist. + + To detect if the column-based attributes on the object have net + changes, and will therefore generate an UPDATE statement, use + ``object_session(instance).is_modified(instance, + include_collections=False)``. + + The event is often called for a batch of objects of the + same class before their UPDATE statements are emitted at + once in a later step. In the extremely rare case that + this is not desirable, the :class:`_orm.Mapper` can be + configured with ``batch=False``, which will cause + batches of instances to be broken up into individual + (and more poorly performing) event->persist->event + steps. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit UPDATE statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being persisted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + def after_update( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance after an UPDATE statement + is emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to modify in-Python-only + state on the instance after an UPDATE occurs, as well + as to emit additional SQL statements on the given + connection. + + This method is called for all instances that are + marked as "dirty", *even those which have no net changes + to their column-based attributes*, and for which + no UPDATE statement has proceeded. An object is marked + as dirty when any of its column-based attributes have a + "set attribute" operation called or when any of its + collections are modified. If, at update time, no + column-based attributes have any net changes, no UPDATE + statement will be issued. This means that an instance + being sent to :meth:`~.MapperEvents.after_update` is + *not* a guarantee that an UPDATE statement has been + issued. + + To detect if the column-based attributes on the object have net + changes, and therefore resulted in an UPDATE statement, use + ``object_session(instance).is_modified(instance, + include_collections=False)``. + + The event is often called for a batch of objects of the + same class after their UPDATE statements have been emitted at + once in a previous step. In the extremely rare case that + this is not desirable, the :class:`_orm.Mapper` can be + configured with ``batch=False``, which will cause + batches of instances to be broken up into individual + (and more poorly performing) event->persist->event + steps. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit UPDATE statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being persisted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + def before_delete( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance before a DELETE statement + is emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to emit additional SQL statements on + the given connection as well as to perform application + specific bookkeeping related to a deletion event. + + The event is often called for a batch of objects of the + same class before their DELETE statements are emitted at + once in a later step. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit DELETE statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being deleted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + def after_delete( + self, mapper: Mapper[_O], connection: Connection, target: _O + ) -> None: + """Receive an object instance after a DELETE statement + has been emitted corresponding to that instance. + + .. note:: this event **only** applies to the + :ref:`session flush operation ` + and does **not** apply to the ORM DML operations described at + :ref:`orm_expression_update_delete`. To intercept ORM + DML events, use :meth:`_orm.SessionEvents.do_orm_execute`. + + This event is used to emit additional SQL statements on + the given connection as well as to perform application + specific bookkeeping related to a deletion event. + + The event is often called for a batch of objects of the + same class after their DELETE statements have been emitted at + once in a previous step. + + .. warning:: + + Mapper-level flush events only allow **very limited operations**, + on attributes local to the row being operated upon only, + as well as allowing any SQL to be emitted on the given + :class:`_engine.Connection`. **Please read fully** the notes + at :ref:`session_persistence_mapper` for guidelines on using + these methods; generally, the :meth:`.SessionEvents.before_flush` + method should be preferred for general on-flush changes. + + :param mapper: the :class:`_orm.Mapper` which is the target + of this event. + :param connection: the :class:`_engine.Connection` being used to + emit DELETE statements for this instance. This + provides a handle into the current transaction on the + target database specific to this instance. + :param target: the mapped instance being deleted. If + the event is configured with ``raw=True``, this will + instead be the :class:`.InstanceState` state-management + object associated with the instance. + :return: No return value is supported by this event. + + .. seealso:: + + :ref:`session_persistence_events` + + """ + + +class _MapperEventsHold(_EventsHold[_ET]): + all_holds = weakref.WeakKeyDictionary() + + def resolve( + self, class_: Union[Type[_T], _InternalEntityType[_T]] + ) -> Optional[Mapper[_T]]: + return _mapper_or_none(class_) + + # this fails on pyright if you use Any. Fails on mypy if you use _ET + class HoldMapperEvents(_EventsHold.HoldEvents[_ET], MapperEvents): # type: ignore[valid-type,misc] # noqa: E501 + pass + + dispatch = event.dispatcher(HoldMapperEvents) + + +_sessionevents_lifecycle_event_names: Set[str] = set() + + +class SessionEvents(event.Events[Session]): + """Define events specific to :class:`.Session` lifecycle. + + e.g.:: + + from sqlalchemy import event + from sqlalchemy.orm import sessionmaker + + + def my_before_commit(session): + print("before commit!") + + + Session = sessionmaker() + + event.listen(Session, "before_commit", my_before_commit) + + The :func:`~.event.listen` function will accept + :class:`.Session` objects as well as the return result + of :class:`~.sessionmaker()` and :class:`~.scoped_session()`. + + Additionally, it accepts the :class:`.Session` class which + will apply listeners to all :class:`.Session` instances + globally. + + :param raw=False: When True, the "target" argument passed + to applicable event listener functions that work on individual + objects will be the instance's :class:`.InstanceState` management + object, rather than the mapped instance itself. + + .. versionadded:: 1.3.14 + + :param restore_load_context=False: Applies to the + :meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader + context of the object when the event hook is complete, so that ongoing + eager load operations continue to target the object appropriately. A + warning is emitted if the object is moved to a new loader context from + within this event if this flag is not set. + + .. versionadded:: 1.3.14 + + """ + + _target_class_doc = "SomeSessionClassOrObject" + + _dispatch_target = Session + + def _lifecycle_event( # type: ignore [misc] + fn: Callable[[SessionEvents, Session, Any], None], + ) -> Callable[[SessionEvents, Session, Any], None]: + _sessionevents_lifecycle_event_names.add(fn.__name__) + return fn + + @classmethod + def _accept_with( # type: ignore [return] + cls, target: Any, identifier: str + ) -> Union[Session, type]: + if isinstance(target, scoped_session): + target = target.session_factory + if not isinstance(target, sessionmaker) and ( + not isinstance(target, type) or not issubclass(target, Session) + ): + raise exc.ArgumentError( + "Session event listen on a scoped_session " + "requires that its creation callable " + "is associated with the Session class." + ) + + if isinstance(target, sessionmaker): + return target.class_ + elif isinstance(target, type): + if issubclass(target, scoped_session): + return Session + elif issubclass(target, Session): + return target + elif isinstance(target, Session): + return target + elif hasattr(target, "_no_async_engine_events"): + target._no_async_engine_events() + else: + # allows alternate SessionEvents-like-classes to be consulted + return event.Events._accept_with(target, identifier) # type: ignore [return-value] # noqa: E501 + + @classmethod + def _listen( + cls, + event_key: Any, + *, + raw: bool = False, + restore_load_context: bool = False, + **kw: Any, + ) -> None: + is_instance_event = ( + event_key.identifier in _sessionevents_lifecycle_event_names + ) + + if is_instance_event: + if not raw or restore_load_context: + fn = event_key._listen_fn + + def wrap( + session: Session, + state: InstanceState[_O], + *arg: Any, + **kw: Any, + ) -> Optional[Any]: + if not raw: + target = state.obj() + if target is None: + # existing behavior is that if the object is + # garbage collected, no event is emitted + return None + else: + target = state # type: ignore [assignment] + if restore_load_context: + runid = state.runid + try: + return fn(session, target, *arg, **kw) + finally: + if restore_load_context: + state.runid = runid + + event_key = event_key.with_wrapper(wrap) + + event_key.base_listen(**kw) + + def do_orm_execute(self, orm_execute_state: ORMExecuteState) -> None: + """Intercept statement executions that occur on behalf of an + ORM :class:`.Session` object. + + This event is invoked for all top-level SQL statements invoked from the + :meth:`_orm.Session.execute` method, as well as related methods such as + :meth:`_orm.Session.scalars` and :meth:`_orm.Session.scalar`. As of + SQLAlchemy 1.4, all ORM queries that run through the + :meth:`_orm.Session.execute` method as well as related methods + :meth:`_orm.Session.scalars`, :meth:`_orm.Session.scalar` etc. + will participate in this event. + This event hook does **not** apply to the queries that are + emitted internally within the ORM flush process, i.e. the + process described at :ref:`session_flushing`. + + .. note:: The :meth:`_orm.SessionEvents.do_orm_execute` event hook + is triggered **for ORM statement executions only**, meaning those + invoked via the :meth:`_orm.Session.execute` and similar methods on + the :class:`_orm.Session` object. It does **not** trigger for + statements that are invoked by SQLAlchemy Core only, i.e. statements + invoked directly using :meth:`_engine.Connection.execute` or + otherwise originating from an :class:`_engine.Engine` object without + any :class:`_orm.Session` involved. To intercept **all** SQL + executions regardless of whether the Core or ORM APIs are in use, + see the event hooks at :class:`.ConnectionEvents`, such as + :meth:`.ConnectionEvents.before_execute` and + :meth:`.ConnectionEvents.before_cursor_execute`. + + Also, this event hook does **not** apply to queries that are + emitted internally within the ORM flush process, + i.e. the process described at :ref:`session_flushing`; to + intercept steps within the flush process, see the event + hooks described at :ref:`session_persistence_events` as + well as :ref:`session_persistence_mapper`. + + This event is a ``do_`` event, meaning it has the capability to replace + the operation that the :meth:`_orm.Session.execute` method normally + performs. The intended use for this includes sharding and + result-caching schemes which may seek to invoke the same statement + across multiple database connections, returning a result that is + merged from each of them, or which don't invoke the statement at all, + instead returning data from a cache. + + The hook intends to replace the use of the + ``Query._execute_and_instances`` method that could be subclassed prior + to SQLAlchemy 1.4. + + :param orm_execute_state: an instance of :class:`.ORMExecuteState` + which contains all information about the current execution, as well + as helper functions used to derive other commonly required + information. See that object for details. + + .. seealso:: + + :ref:`session_execute_events` - top level documentation on how + to use :meth:`_orm.SessionEvents.do_orm_execute` + + :class:`.ORMExecuteState` - the object passed to the + :meth:`_orm.SessionEvents.do_orm_execute` event which contains + all information about the statement to be invoked. It also + provides an interface to extend the current statement, options, + and parameters as well as an option that allows programmatic + invocation of the statement at any point. + + :ref:`examples_session_orm_events` - includes examples of using + :meth:`_orm.SessionEvents.do_orm_execute` + + :ref:`examples_caching` - an example of how to integrate + Dogpile caching with the ORM :class:`_orm.Session` making use + of the :meth:`_orm.SessionEvents.do_orm_execute` event hook. + + :ref:`examples_sharding` - the Horizontal Sharding example / + extension relies upon the + :meth:`_orm.SessionEvents.do_orm_execute` event hook to invoke a + SQL statement on multiple backends and return a merged result. + + + .. versionadded:: 1.4 + + """ + + def after_transaction_create( + self, session: Session, transaction: SessionTransaction + ) -> None: + """Execute when a new :class:`.SessionTransaction` is created. + + This event differs from :meth:`~.SessionEvents.after_begin` + in that it occurs for each :class:`.SessionTransaction` + overall, as opposed to when transactions are begun + on individual database connections. It is also invoked + for nested transactions and subtransactions, and is always + matched by a corresponding + :meth:`~.SessionEvents.after_transaction_end` event + (assuming normal operation of the :class:`.Session`). + + :param session: the target :class:`.Session`. + :param transaction: the target :class:`.SessionTransaction`. + + To detect if this is the outermost + :class:`.SessionTransaction`, as opposed to a "subtransaction" or a + SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute + is ``None``:: + + @event.listens_for(session, "after_transaction_create") + def after_transaction_create(session, transaction): + if transaction.parent is None: + ... # work with top-level transaction + + To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the + :attr:`.SessionTransaction.nested` attribute:: + + @event.listens_for(session, "after_transaction_create") + def after_transaction_create(session, transaction): + if transaction.nested: + ... # work with SAVEPOINT transaction + + .. seealso:: + + :class:`.SessionTransaction` + + :meth:`~.SessionEvents.after_transaction_end` + + """ + + def after_transaction_end( + self, session: Session, transaction: SessionTransaction + ) -> None: + """Execute when the span of a :class:`.SessionTransaction` ends. + + This event differs from :meth:`~.SessionEvents.after_commit` + in that it corresponds to all :class:`.SessionTransaction` + objects in use, including those for nested transactions + and subtransactions, and is always matched by a corresponding + :meth:`~.SessionEvents.after_transaction_create` event. + + :param session: the target :class:`.Session`. + :param transaction: the target :class:`.SessionTransaction`. + + To detect if this is the outermost + :class:`.SessionTransaction`, as opposed to a "subtransaction" or a + SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute + is ``None``:: + + @event.listens_for(session, "after_transaction_create") + def after_transaction_end(session, transaction): + if transaction.parent is None: + ... # work with top-level transaction + + To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the + :attr:`.SessionTransaction.nested` attribute:: + + @event.listens_for(session, "after_transaction_create") + def after_transaction_end(session, transaction): + if transaction.nested: + ... # work with SAVEPOINT transaction + + .. seealso:: + + :class:`.SessionTransaction` + + :meth:`~.SessionEvents.after_transaction_create` + + """ + + def before_commit(self, session: Session) -> None: + """Execute before commit is called. + + .. note:: + + The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush, + that is, the :class:`.Session` can emit SQL to the database + many times within the scope of a transaction. + For interception of these events, use the + :meth:`~.SessionEvents.before_flush`, + :meth:`~.SessionEvents.after_flush`, or + :meth:`~.SessionEvents.after_flush_postexec` + events. + + :param session: The target :class:`.Session`. + + .. seealso:: + + :meth:`~.SessionEvents.after_commit` + + :meth:`~.SessionEvents.after_begin` + + :meth:`~.SessionEvents.after_transaction_create` + + :meth:`~.SessionEvents.after_transaction_end` + + """ + + def after_commit(self, session: Session) -> None: + """Execute after a commit has occurred. + + .. note:: + + The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush, + that is, the :class:`.Session` can emit SQL to the database + many times within the scope of a transaction. + For interception of these events, use the + :meth:`~.SessionEvents.before_flush`, + :meth:`~.SessionEvents.after_flush`, or + :meth:`~.SessionEvents.after_flush_postexec` + events. + + .. note:: + + The :class:`.Session` is not in an active transaction + when the :meth:`~.SessionEvents.after_commit` event is invoked, + and therefore can not emit SQL. To emit SQL corresponding to + every transaction, use the :meth:`~.SessionEvents.before_commit` + event. + + :param session: The target :class:`.Session`. + + .. seealso:: + + :meth:`~.SessionEvents.before_commit` + + :meth:`~.SessionEvents.after_begin` + + :meth:`~.SessionEvents.after_transaction_create` + + :meth:`~.SessionEvents.after_transaction_end` + + """ + + def after_rollback(self, session: Session) -> None: + """Execute after a real DBAPI rollback has occurred. + + Note that this event only fires when the *actual* rollback against + the database occurs - it does *not* fire each time the + :meth:`.Session.rollback` method is called, if the underlying + DBAPI transaction has already been rolled back. In many + cases, the :class:`.Session` will not be in + an "active" state during this event, as the current + transaction is not valid. To acquire a :class:`.Session` + which is active after the outermost rollback has proceeded, + use the :meth:`.SessionEvents.after_soft_rollback` event, checking the + :attr:`.Session.is_active` flag. + + :param session: The target :class:`.Session`. + + """ + + def after_soft_rollback( + self, session: Session, previous_transaction: SessionTransaction + ) -> None: + """Execute after any rollback has occurred, including "soft" + rollbacks that don't actually emit at the DBAPI level. + + This corresponds to both nested and outer rollbacks, i.e. + the innermost rollback that calls the DBAPI's + rollback() method, as well as the enclosing rollback + calls that only pop themselves from the transaction stack. + + The given :class:`.Session` can be used to invoke SQL and + :meth:`.Session.query` operations after an outermost rollback + by first checking the :attr:`.Session.is_active` flag:: + + @event.listens_for(Session, "after_soft_rollback") + def do_something(session, previous_transaction): + if session.is_active: + session.execute(text("select * from some_table")) + + :param session: The target :class:`.Session`. + :param previous_transaction: The :class:`.SessionTransaction` + transactional marker object which was just closed. The current + :class:`.SessionTransaction` for the given :class:`.Session` is + available via the :attr:`.Session.transaction` attribute. + + """ + + def before_flush( + self, + session: Session, + flush_context: UOWTransaction, + instances: Optional[Sequence[_O]], + ) -> None: + """Execute before flush process has started. + + :param session: The target :class:`.Session`. + :param flush_context: Internal :class:`.UOWTransaction` object + which handles the details of the flush. + :param instances: Usually ``None``, this is the collection of + objects which can be passed to the :meth:`.Session.flush` method + (note this usage is deprecated). + + .. seealso:: + + :meth:`~.SessionEvents.after_flush` + + :meth:`~.SessionEvents.after_flush_postexec` + + :ref:`session_persistence_events` + + """ + + def after_flush( + self, session: Session, flush_context: UOWTransaction + ) -> None: + """Execute after flush has completed, but before commit has been + called. + + Note that the session's state is still in pre-flush, i.e. 'new', + 'dirty', and 'deleted' lists still show pre-flush state as well + as the history settings on instance attributes. + + .. warning:: This event runs after the :class:`.Session` has emitted + SQL to modify the database, but **before** it has altered its + internal state to reflect those changes, including that newly + inserted objects are placed into the identity map. ORM operations + emitted within this event such as loads of related items + may produce new identity map entries that will immediately + be replaced, sometimes causing confusing results. SQLAlchemy will + emit a warning for this condition as of version 1.3.9. + + :param session: The target :class:`.Session`. + :param flush_context: Internal :class:`.UOWTransaction` object + which handles the details of the flush. + + .. seealso:: + + :meth:`~.SessionEvents.before_flush` + + :meth:`~.SessionEvents.after_flush_postexec` + + :ref:`session_persistence_events` + + """ + + def after_flush_postexec( + self, session: Session, flush_context: UOWTransaction + ) -> None: + """Execute after flush has completed, and after the post-exec + state occurs. + + This will be when the 'new', 'dirty', and 'deleted' lists are in + their final state. An actual commit() may or may not have + occurred, depending on whether or not the flush started its own + transaction or participated in a larger transaction. + + :param session: The target :class:`.Session`. + :param flush_context: Internal :class:`.UOWTransaction` object + which handles the details of the flush. + + + .. seealso:: + + :meth:`~.SessionEvents.before_flush` + + :meth:`~.SessionEvents.after_flush` + + :ref:`session_persistence_events` + + """ + + def after_begin( + self, + session: Session, + transaction: SessionTransaction, + connection: Connection, + ) -> None: + """Execute after a transaction is begun on a connection. + + .. note:: This event is called within the process of the + :class:`_orm.Session` modifying its own internal state. + To invoke SQL operations within this hook, use the + :class:`_engine.Connection` provided to the event; + do not run SQL operations using the :class:`_orm.Session` + directly. + + :param session: The target :class:`.Session`. + :param transaction: The :class:`.SessionTransaction`. + :param connection: The :class:`_engine.Connection` object + which will be used for SQL statements. + + .. seealso:: + + :meth:`~.SessionEvents.before_commit` + + :meth:`~.SessionEvents.after_commit` + + :meth:`~.SessionEvents.after_transaction_create` + + :meth:`~.SessionEvents.after_transaction_end` + + """ + + @_lifecycle_event + def before_attach(self, session: Session, instance: _O) -> None: + """Execute before an instance is attached to a session. + + This is called before an add, delete or merge causes + the object to be part of the session. + + .. seealso:: + + :meth:`~.SessionEvents.after_attach` + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def after_attach(self, session: Session, instance: _O) -> None: + """Execute after an instance is attached to a session. + + This is called after an add, delete or merge. + + .. note:: + + As of 0.8, this event fires off *after* the item + has been fully associated with the session, which is + different than previous releases. For event + handlers that require the object not yet + be part of session state (such as handlers which + may autoflush while the target object is not + yet complete) consider the + new :meth:`.before_attach` event. + + .. seealso:: + + :meth:`~.SessionEvents.before_attach` + + :ref:`session_lifecycle_events` + + """ + + @event._legacy_signature( + "0.9", + ["session", "query", "query_context", "result"], + lambda update_context: ( + update_context.session, + update_context.query, + None, + update_context.result, + ), + ) + def after_bulk_update(self, update_context: _O) -> None: + """Event for after the legacy :meth:`_orm.Query.update` method + has been called. + + .. legacy:: The :meth:`_orm.SessionEvents.after_bulk_update` method + is a legacy event hook as of SQLAlchemy 2.0. The event + **does not participate** in :term:`2.0 style` invocations + using :func:`_dml.update` documented at + :ref:`orm_queryguide_update_delete_where`. For 2.0 style use, + the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept + these calls. + + :param update_context: an "update context" object which contains + details about the update, including these attributes: + + * ``session`` - the :class:`.Session` involved + * ``query`` -the :class:`_query.Query` + object that this update operation + was called upon. + * ``values`` The "values" dictionary that was passed to + :meth:`_query.Query.update`. + * ``result`` the :class:`_engine.CursorResult` + returned as a result of the + bulk UPDATE operation. + + .. versionchanged:: 1.4 the update_context no longer has a + ``QueryContext`` object associated with it. + + .. seealso:: + + :meth:`.QueryEvents.before_compile_update` + + :meth:`.SessionEvents.after_bulk_delete` + + """ + + @event._legacy_signature( + "0.9", + ["session", "query", "query_context", "result"], + lambda delete_context: ( + delete_context.session, + delete_context.query, + None, + delete_context.result, + ), + ) + def after_bulk_delete(self, delete_context: _O) -> None: + """Event for after the legacy :meth:`_orm.Query.delete` method + has been called. + + .. legacy:: The :meth:`_orm.SessionEvents.after_bulk_delete` method + is a legacy event hook as of SQLAlchemy 2.0. The event + **does not participate** in :term:`2.0 style` invocations + using :func:`_dml.delete` documented at + :ref:`orm_queryguide_update_delete_where`. For 2.0 style use, + the :meth:`_orm.SessionEvents.do_orm_execute` hook will intercept + these calls. + + :param delete_context: a "delete context" object which contains + details about the update, including these attributes: + + * ``session`` - the :class:`.Session` involved + * ``query`` -the :class:`_query.Query` + object that this update operation + was called upon. + * ``result`` the :class:`_engine.CursorResult` + returned as a result of the + bulk DELETE operation. + + .. versionchanged:: 1.4 the update_context no longer has a + ``QueryContext`` object associated with it. + + .. seealso:: + + :meth:`.QueryEvents.before_compile_delete` + + :meth:`.SessionEvents.after_bulk_update` + + """ + + @_lifecycle_event + def transient_to_pending(self, session: Session, instance: _O) -> None: + """Intercept the "transient to pending" transition for a specific + object. + + This event is a specialization of the + :meth:`.SessionEvents.after_attach` event which is only invoked + for this specific transition. It is invoked typically during the + :meth:`.Session.add` call. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def pending_to_transient(self, session: Session, instance: _O) -> None: + """Intercept the "pending to transient" transition for a specific + object. + + This less common transition occurs when an pending object that has + not been flushed is evicted from the session; this can occur + when the :meth:`.Session.rollback` method rolls back the transaction, + or when the :meth:`.Session.expunge` method is used. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def persistent_to_transient(self, session: Session, instance: _O) -> None: + """Intercept the "persistent to transient" transition for a specific + object. + + This less common transition occurs when an pending object that has + has been flushed is evicted from the session; this can occur + when the :meth:`.Session.rollback` method rolls back the transaction. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def pending_to_persistent(self, session: Session, instance: _O) -> None: + """Intercept the "pending to persistent"" transition for a specific + object. + + This event is invoked within the flush process, and is + similar to scanning the :attr:`.Session.new` collection within + the :meth:`.SessionEvents.after_flush` event. However, in this + case the object has already been moved to the persistent state + when the event is called. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def detached_to_persistent(self, session: Session, instance: _O) -> None: + """Intercept the "detached to persistent" transition for a specific + object. + + This event is a specialization of the + :meth:`.SessionEvents.after_attach` event which is only invoked + for this specific transition. It is invoked typically during the + :meth:`.Session.add` call, as well as during the + :meth:`.Session.delete` call if the object was not previously + associated with the + :class:`.Session` (note that an object marked as "deleted" remains + in the "persistent" state until the flush proceeds). + + .. note:: + + If the object becomes persistent as part of a call to + :meth:`.Session.delete`, the object is **not** yet marked as + deleted when this event is called. To detect deleted objects, + check the ``deleted`` flag sent to the + :meth:`.SessionEvents.persistent_to_detached` to event after the + flush proceeds, or check the :attr:`.Session.deleted` collection + within the :meth:`.SessionEvents.before_flush` event if deleted + objects need to be intercepted before the flush. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def loaded_as_persistent(self, session: Session, instance: _O) -> None: + """Intercept the "loaded as persistent" transition for a specific + object. + + This event is invoked within the ORM loading process, and is invoked + very similarly to the :meth:`.InstanceEvents.load` event. However, + the event here is linkable to a :class:`.Session` class or instance, + rather than to a mapper or class hierarchy, and integrates + with the other session lifecycle events smoothly. The object + is guaranteed to be present in the session's identity map when + this event is called. + + .. note:: This event is invoked within the loader process before + eager loaders may have been completed, and the object's state may + not be complete. Additionally, invoking row-level refresh + operations on the object will place the object into a new loader + context, interfering with the existing load context. See the note + on :meth:`.InstanceEvents.load` for background on making use of the + :paramref:`.SessionEvents.restore_load_context` parameter, which + works in the same manner as that of + :paramref:`.InstanceEvents.restore_load_context`, in order to + resolve this scenario. + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def persistent_to_deleted(self, session: Session, instance: _O) -> None: + """Intercept the "persistent to deleted" transition for a specific + object. + + This event is invoked when a persistent object's identity + is deleted from the database within a flush, however the object + still remains associated with the :class:`.Session` until the + transaction completes. + + If the transaction is rolled back, the object moves again + to the persistent state, and the + :meth:`.SessionEvents.deleted_to_persistent` event is called. + If the transaction is committed, the object becomes detached, + which will emit the :meth:`.SessionEvents.deleted_to_detached` + event. + + Note that while the :meth:`.Session.delete` method is the primary + public interface to mark an object as deleted, many objects + get deleted due to cascade rules, which are not always determined + until flush time. Therefore, there's no way to catch + every object that will be deleted until the flush has proceeded. + the :meth:`.SessionEvents.persistent_to_deleted` event is therefore + invoked at the end of a flush. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def deleted_to_persistent(self, session: Session, instance: _O) -> None: + """Intercept the "deleted to persistent" transition for a specific + object. + + This transition occurs only when an object that's been deleted + successfully in a flush is restored due to a call to + :meth:`.Session.rollback`. The event is not called under + any other circumstances. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def deleted_to_detached(self, session: Session, instance: _O) -> None: + """Intercept the "deleted to detached" transition for a specific + object. + + This event is invoked when a deleted object is evicted + from the session. The typical case when this occurs is when + the transaction for a :class:`.Session` in which the object + was deleted is committed; the object moves from the deleted + state to the detached state. + + It is also invoked for objects that were deleted in a flush + when the :meth:`.Session.expunge_all` or :meth:`.Session.close` + events are called, as well as if the object is individually + expunged from its deleted state via :meth:`.Session.expunge`. + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + @_lifecycle_event + def persistent_to_detached(self, session: Session, instance: _O) -> None: + """Intercept the "persistent to detached" transition for a specific + object. + + This event is invoked when a persistent object is evicted + from the session. There are many conditions that cause this + to happen, including: + + * using a method such as :meth:`.Session.expunge` + or :meth:`.Session.close` + + * Calling the :meth:`.Session.rollback` method, when the object + was part of an INSERT statement for that session's transaction + + + :param session: target :class:`.Session` + + :param instance: the ORM-mapped instance being operated upon. + + :param deleted: boolean. If True, indicates this object moved + to the detached state because it was marked as deleted and flushed. + + + .. seealso:: + + :ref:`session_lifecycle_events` + + """ + + +class AttributeEvents(event.Events[QueryableAttribute[Any]]): + r"""Define events for object attributes. + + These are typically defined on the class-bound descriptor for the + target class. + + For example, to register a listener that will receive the + :meth:`_orm.AttributeEvents.append` event:: + + from sqlalchemy import event + + + @event.listens_for(MyClass.collection, "append", propagate=True) + def my_append_listener(target, value, initiator): + print("received append event for target: %s" % target) + + Listeners have the option to return a possibly modified version of the + value, when the :paramref:`.AttributeEvents.retval` flag is passed to + :func:`.event.listen` or :func:`.event.listens_for`, such as below, + illustrated using the :meth:`_orm.AttributeEvents.set` event:: + + def validate_phone(target, value, oldvalue, initiator): + "Strip non-numeric characters from a phone number" + + return re.sub(r"\D", "", value) + + + # setup listener on UserContact.phone attribute, instructing + # it to use the return value + listen(UserContact.phone, "set", validate_phone, retval=True) + + A validation function like the above can also raise an exception + such as :exc:`ValueError` to halt the operation. + + The :paramref:`.AttributeEvents.propagate` flag is also important when + applying listeners to mapped classes that also have mapped subclasses, + as when using mapper inheritance patterns:: + + + @event.listens_for(MySuperClass.attr, "set", propagate=True) + def receive_set(target, value, initiator): + print("value set: %s" % target) + + The full list of modifiers available to the :func:`.event.listen` + and :func:`.event.listens_for` functions are below. + + :param active_history=False: When True, indicates that the + "set" event would like to receive the "old" value being + replaced unconditionally, even if this requires firing off + database loads. Note that ``active_history`` can also be + set directly via :func:`.column_property` and + :func:`_orm.relationship`. + + :param propagate=False: When True, the listener function will + be established not just for the class attribute given, but + for attributes of the same name on all current subclasses + of that class, as well as all future subclasses of that + class, using an additional listener that listens for + instrumentation events. + :param raw=False: When True, the "target" argument to the + event will be the :class:`.InstanceState` management + object, rather than the mapped instance itself. + :param retval=False: when True, the user-defined event + listening must return the "value" argument from the + function. This gives the listening function the opportunity + to change the value that is ultimately used for a "set" + or "append" event. + + """ + + _target_class_doc = "SomeClass.some_attribute" + _dispatch_target = QueryableAttribute + + @staticmethod + def _set_dispatch( + cls: Type[_HasEventsDispatch[Any]], dispatch_cls: Type[_Dispatch[Any]] + ) -> _Dispatch[Any]: + dispatch = event.Events._set_dispatch(cls, dispatch_cls) + dispatch_cls._active_history = False + return dispatch + + @classmethod + def _accept_with( + cls, + target: Union[QueryableAttribute[Any], Type[QueryableAttribute[Any]]], + identifier: str, + ) -> Union[QueryableAttribute[Any], Type[QueryableAttribute[Any]]]: + # TODO: coverage + if isinstance(target, interfaces.MapperProperty): + return getattr(target.parent.class_, target.key) + else: + return target + + @classmethod + def _listen( # type: ignore [override] + cls, + event_key: _EventKey[QueryableAttribute[Any]], + active_history: bool = False, + raw: bool = False, + retval: bool = False, + propagate: bool = False, + include_key: bool = False, + ) -> None: + target, fn = event_key.dispatch_target, event_key._listen_fn + + if active_history: + target.dispatch._active_history = True + + if not raw or not retval or not include_key: + + def wrap(target: InstanceState[_O], *arg: Any, **kw: Any) -> Any: + if not raw: + target = target.obj() # type: ignore [assignment] + if not retval: + if arg: + value = arg[0] + else: + value = None + if include_key: + fn(target, *arg, **kw) + else: + fn(target, *arg) + return value + else: + if include_key: + return fn(target, *arg, **kw) + else: + return fn(target, *arg) + + event_key = event_key.with_wrapper(wrap) + + event_key.base_listen(propagate=propagate) + + if propagate: + manager = instrumentation.manager_of_class(target.class_) + + for mgr in manager.subclass_managers(True): # type: ignore [no-untyped-call] # noqa: E501 + event_key.with_dispatch_target(mgr[target.key]).base_listen( + propagate=True + ) + if active_history: + mgr[target.key].dispatch._active_history = True + + def append( + self, + target: _O, + value: _T, + initiator: Event, + *, + key: EventConstants = NO_KEY, + ) -> Optional[_T]: + """Receive a collection append event. + + The append event is invoked for each element as it is appended + to the collection. This occurs for single-item appends as well + as for a "bulk replace" operation. + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: the value being appended. If this listener + is registered with ``retval=True``, the listener + function must return this value, or a new value which + replaces it. + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. May be modified + from its original value by backref handlers in order to control + chained event propagation, as well as be inspected for information + about the source of the event. + :param key: When the event is established using the + :paramref:`.AttributeEvents.include_key` parameter set to + True, this will be the key used in the operation, such as + ``collection[some_key_or_index] = value``. + The parameter is not passed + to the event at all if the the + :paramref:`.AttributeEvents.include_key` + was not used to set up the event; this is to allow backwards + compatibility with existing event handlers that don't include the + ``key`` parameter. + + .. versionadded:: 2.0 + + :return: if the event was registered with ``retval=True``, + the given value, or a new effective value, should be returned. + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + :meth:`.AttributeEvents.bulk_replace` + + """ + + def append_wo_mutation( + self, + target: _O, + value: _T, + initiator: Event, + *, + key: EventConstants = NO_KEY, + ) -> None: + """Receive a collection append event where the collection was not + actually mutated. + + This event differs from :meth:`_orm.AttributeEvents.append` in that + it is fired off for de-duplicating collections such as sets and + dictionaries, when the object already exists in the target collection. + The event does not have a return value and the identity of the + given object cannot be changed. + + The event is used for cascading objects into a :class:`_orm.Session` + when the collection has already been mutated via a backref event. + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: the value that would be appended if the object did not + already exist in the collection. + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. May be modified + from its original value by backref handlers in order to control + chained event propagation, as well as be inspected for information + about the source of the event. + :param key: When the event is established using the + :paramref:`.AttributeEvents.include_key` parameter set to + True, this will be the key used in the operation, such as + ``collection[some_key_or_index] = value``. + The parameter is not passed + to the event at all if the the + :paramref:`.AttributeEvents.include_key` + was not used to set up the event; this is to allow backwards + compatibility with existing event handlers that don't include the + ``key`` parameter. + + .. versionadded:: 2.0 + + :return: No return value is defined for this event. + + .. versionadded:: 1.4.15 + + """ + + def bulk_replace( + self, + target: _O, + values: Iterable[_T], + initiator: Event, + *, + keys: Optional[Iterable[EventConstants]] = None, + ) -> None: + """Receive a collection 'bulk replace' event. + + This event is invoked for a sequence of values as they are incoming + to a bulk collection set operation, which can be + modified in place before the values are treated as ORM objects. + This is an "early hook" that runs before the bulk replace routine + attempts to reconcile which objects are already present in the + collection and which are being removed by the net replace operation. + + It is typical that this method be combined with use of the + :meth:`.AttributeEvents.append` event. When using both of these + events, note that a bulk replace operation will invoke + the :meth:`.AttributeEvents.append` event for all new items, + even after :meth:`.AttributeEvents.bulk_replace` has been invoked + for the collection as a whole. In order to determine if an + :meth:`.AttributeEvents.append` event is part of a bulk replace, + use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the + incoming initiator:: + + from sqlalchemy.orm.attributes import OP_BULK_REPLACE + + + @event.listens_for(SomeObject.collection, "bulk_replace") + def process_collection(target, values, initiator): + values[:] = [_make_value(value) for value in values] + + + @event.listens_for(SomeObject.collection, "append", retval=True) + def process_collection(target, value, initiator): + # make sure bulk_replace didn't already do it + if initiator is None or initiator.op is not OP_BULK_REPLACE: + return _make_value(value) + else: + return value + + .. versionadded:: 1.2 + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: a sequence (e.g. a list) of the values being set. The + handler can modify this list in place. + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. + :param keys: When the event is established using the + :paramref:`.AttributeEvents.include_key` parameter set to + True, this will be the sequence of keys used in the operation, + typically only for a dictionary update. The parameter is not passed + to the event at all if the the + :paramref:`.AttributeEvents.include_key` + was not used to set up the event; this is to allow backwards + compatibility with existing event handlers that don't include the + ``key`` parameter. + + .. versionadded:: 2.0 + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + + """ + + def remove( + self, + target: _O, + value: _T, + initiator: Event, + *, + key: EventConstants = NO_KEY, + ) -> None: + """Receive a collection remove event. + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: the value being removed. + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. May be modified + from its original value by backref handlers in order to control + chained event propagation. + + :param key: When the event is established using the + :paramref:`.AttributeEvents.include_key` parameter set to + True, this will be the key used in the operation, such as + ``del collection[some_key_or_index]``. The parameter is not passed + to the event at all if the the + :paramref:`.AttributeEvents.include_key` + was not used to set up the event; this is to allow backwards + compatibility with existing event handlers that don't include the + ``key`` parameter. + + .. versionadded:: 2.0 + + :return: No return value is defined for this event. + + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + """ + + def set( + self, target: _O, value: _T, oldvalue: _T, initiator: Event + ) -> None: + """Receive a scalar set event. + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: the value being set. If this listener + is registered with ``retval=True``, the listener + function must return this value, or a new value which + replaces it. + :param oldvalue: the previous value being replaced. This + may also be the symbol ``NEVER_SET`` or ``NO_VALUE``. + If the listener is registered with ``active_history=True``, + the previous value of the attribute will be loaded from + the database if the existing value is currently unloaded + or expired. + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. May be modified + from its original value by backref handlers in order to control + chained event propagation. + + :return: if the event was registered with ``retval=True``, + the given value, or a new effective value, should be returned. + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + """ + + def init_scalar( + self, target: _O, value: _T, dict_: Dict[Any, Any] + ) -> None: + r"""Receive a scalar "init" event. + + This event is invoked when an uninitialized, unpersisted scalar + attribute is accessed, e.g. read:: + + + x = my_object.some_attribute + + The ORM's default behavior when this occurs for an un-initialized + attribute is to return the value ``None``; note this differs from + Python's usual behavior of raising ``AttributeError``. The + event here can be used to customize what value is actually returned, + with the assumption that the event listener would be mirroring + a default generator that is configured on the Core + :class:`_schema.Column` + object as well. + + Since a default generator on a :class:`_schema.Column` + might also produce + a changing value such as a timestamp, the + :meth:`.AttributeEvents.init_scalar` + event handler can also be used to **set** the newly returned value, so + that a Core-level default generation function effectively fires off + only once, but at the moment the attribute is accessed on the + non-persisted object. Normally, no change to the object's state + is made when an uninitialized attribute is accessed (much older + SQLAlchemy versions did in fact change the object's state). + + If a default generator on a column returned a particular constant, + a handler might be used as follows:: + + SOME_CONSTANT = 3.1415926 + + + class MyClass(Base): + # ... + + some_attribute = Column(Numeric, default=SOME_CONSTANT) + + + @event.listens_for( + MyClass.some_attribute, "init_scalar", retval=True, propagate=True + ) + def _init_some_attribute(target, dict_, value): + dict_["some_attribute"] = SOME_CONSTANT + return SOME_CONSTANT + + Above, we initialize the attribute ``MyClass.some_attribute`` to the + value of ``SOME_CONSTANT``. The above code includes the following + features: + + * By setting the value ``SOME_CONSTANT`` in the given ``dict_``, + we indicate that this value is to be persisted to the database. + This supersedes the use of ``SOME_CONSTANT`` in the default generator + for the :class:`_schema.Column`. The ``active_column_defaults.py`` + example given at :ref:`examples_instrumentation` illustrates using + the same approach for a changing default, e.g. a timestamp + generator. In this particular example, it is not strictly + necessary to do this since ``SOME_CONSTANT`` would be part of the + INSERT statement in either case. + + * By establishing the ``retval=True`` flag, the value we return + from the function will be returned by the attribute getter. + Without this flag, the event is assumed to be a passive observer + and the return value of our function is ignored. + + * The ``propagate=True`` flag is significant if the mapped class + includes inheriting subclasses, which would also make use of this + event listener. Without this flag, an inheriting subclass will + not use our event handler. + + In the above example, the attribute set event + :meth:`.AttributeEvents.set` as well as the related validation feature + provided by :obj:`_orm.validates` is **not** invoked when we apply our + value to the given ``dict_``. To have these events to invoke in + response to our newly generated value, apply the value to the given + object as a normal attribute set operation:: + + SOME_CONSTANT = 3.1415926 + + + @event.listens_for( + MyClass.some_attribute, "init_scalar", retval=True, propagate=True + ) + def _init_some_attribute(target, dict_, value): + # will also fire off attribute set events + target.some_attribute = SOME_CONSTANT + return SOME_CONSTANT + + When multiple listeners are set up, the generation of the value + is "chained" from one listener to the next by passing the value + returned by the previous listener that specifies ``retval=True`` + as the ``value`` argument of the next listener. + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param value: the value that is to be returned before this event + listener were invoked. This value begins as the value ``None``, + however will be the return value of the previous event handler + function if multiple listeners are present. + :param dict\_: the attribute dictionary of this mapped object. + This is normally the ``__dict__`` of the object, but in all cases + represents the destination that the attribute system uses to get + at the actual value of this attribute. Placing the value in this + dictionary has the effect that the value will be used in the + INSERT statement generated by the unit of work. + + + .. seealso:: + + :meth:`.AttributeEvents.init_collection` - collection version + of this event + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + :ref:`examples_instrumentation` - see the + ``active_column_defaults.py`` example. + + """ # noqa: E501 + + def init_collection( + self, + target: _O, + collection: Type[Collection[Any]], + collection_adapter: CollectionAdapter, + ) -> None: + """Receive a 'collection init' event. + + This event is triggered for a collection-based attribute, when + the initial "empty collection" is first generated for a blank + attribute, as well as for when the collection is replaced with + a new one, such as via a set event. + + E.g., given that ``User.addresses`` is a relationship-based + collection, the event is triggered here:: + + u1 = User() + u1.addresses.append(a1) # <- new collection + + and also during replace operations:: + + u1.addresses = [a2, a3] # <- new collection + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + :param collection: the new collection. This will always be generated + from what was specified as + :paramref:`_orm.relationship.collection_class`, and will always + be empty. + :param collection_adapter: the :class:`.CollectionAdapter` that will + mediate internal access to the collection. + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + :meth:`.AttributeEvents.init_scalar` - "scalar" version of this + event. + + """ + + def dispose_collection( + self, + target: _O, + collection: Collection[Any], + collection_adapter: CollectionAdapter, + ) -> None: + """Receive a 'collection dispose' event. + + This event is triggered for a collection-based attribute when + a collection is replaced, that is:: + + u1.addresses.append(a1) + + u1.addresses = [a2, a3] # <- old collection is disposed + + The old collection received will contain its previous contents. + + .. versionchanged:: 1.2 The collection passed to + :meth:`.AttributeEvents.dispose_collection` will now have its + contents before the dispose intact; previously, the collection + would be empty. + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + """ + + def modified(self, target: _O, initiator: Event) -> None: + """Receive a 'modified' event. + + This event is triggered when the :func:`.attributes.flag_modified` + function is used to trigger a modify event on an attribute without + any specific value being set. + + .. versionadded:: 1.2 + + :param target: the object instance receiving the event. + If the listener is registered with ``raw=True``, this will + be the :class:`.InstanceState` object. + + :param initiator: An instance of :class:`.attributes.Event` + representing the initiation of the event. + + .. seealso:: + + :class:`.AttributeEvents` - background on listener options such + as propagation to subclasses. + + """ + + +class QueryEvents(event.Events[Query[Any]]): + """Represent events within the construction of a :class:`_query.Query` + object. + + .. legacy:: The :class:`_orm.QueryEvents` event methods are legacy + as of SQLAlchemy 2.0, and only apply to direct use of the + :class:`_orm.Query` object. They are not used for :term:`2.0 style` + statements. For events to intercept and modify 2.0 style ORM use, + use the :meth:`_orm.SessionEvents.do_orm_execute` hook. + + + The :class:`_orm.QueryEvents` hooks are now superseded by the + :meth:`_orm.SessionEvents.do_orm_execute` event hook. + + """ + + _target_class_doc = "SomeQuery" + _dispatch_target = Query + + def before_compile(self, query: Query[Any]) -> None: + """Receive the :class:`_query.Query` + object before it is composed into a + core :class:`_expression.Select` object. + + .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile` event + is superseded by the much more capable + :meth:`_orm.SessionEvents.do_orm_execute` hook. In version 1.4, + the :meth:`_orm.QueryEvents.before_compile` event is **no longer + used** for ORM-level attribute loads, such as loads of deferred + or expired attributes as well as relationship loaders. See the + new examples in :ref:`examples_session_orm_events` which + illustrate new ways of intercepting and modifying ORM queries + for the most common purpose of adding arbitrary filter criteria. + + + This event is intended to allow changes to the query given:: + + @event.listens_for(Query, "before_compile", retval=True) + def no_deleted(query): + for desc in query.column_descriptions: + if desc["type"] is User: + entity = desc["entity"] + query = query.filter(entity.deleted == False) + return query + + The event should normally be listened with the ``retval=True`` + parameter set, so that the modified query may be returned. + + The :meth:`.QueryEvents.before_compile` event by default + will disallow "baked" queries from caching a query, if the event + hook returns a new :class:`_query.Query` object. + This affects both direct + use of the baked query extension as well as its operation within + lazy loaders and eager loaders for relationships. In order to + re-establish the query being cached, apply the event adding the + ``bake_ok`` flag:: + + @event.listens_for(Query, "before_compile", retval=True, bake_ok=True) + def my_event(query): + for desc in query.column_descriptions: + if desc["type"] is User: + entity = desc["entity"] + query = query.filter(entity.deleted == False) + return query + + When ``bake_ok`` is set to True, the event hook will only be invoked + once, and not called for subsequent invocations of a particular query + that is being cached. + + .. versionadded:: 1.3.11 - added the "bake_ok" flag to the + :meth:`.QueryEvents.before_compile` event and disallowed caching via + the "baked" extension from occurring for event handlers that + return a new :class:`_query.Query` object if this flag is not set. + + .. seealso:: + + :meth:`.QueryEvents.before_compile_update` + + :meth:`.QueryEvents.before_compile_delete` + + :ref:`baked_with_before_compile` + + """ # noqa: E501 + + def before_compile_update( + self, query: Query[Any], update_context: BulkUpdate + ) -> None: + """Allow modifications to the :class:`_query.Query` object within + :meth:`_query.Query.update`. + + .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile_update` + event is superseded by the much more capable + :meth:`_orm.SessionEvents.do_orm_execute` hook. + + Like the :meth:`.QueryEvents.before_compile` event, if the event + is to be used to alter the :class:`_query.Query` object, it should + be configured with ``retval=True``, and the modified + :class:`_query.Query` object returned, as in :: + + @event.listens_for(Query, "before_compile_update", retval=True) + def no_deleted(query, update_context): + for desc in query.column_descriptions: + if desc["type"] is User: + entity = desc["entity"] + query = query.filter(entity.deleted == False) + + update_context.values["timestamp"] = datetime.datetime.now( + datetime.UTC + ) + return query + + The ``.values`` dictionary of the "update context" object can also + be modified in place as illustrated above. + + :param query: a :class:`_query.Query` instance; this is also + the ``.query`` attribute of the given "update context" + object. + + :param update_context: an "update context" object which is + the same kind of object as described in + :paramref:`.QueryEvents.after_bulk_update.update_context`. + The object has a ``.values`` attribute in an UPDATE context which is + the dictionary of parameters passed to :meth:`_query.Query.update`. + This + dictionary can be modified to alter the VALUES clause of the + resulting UPDATE statement. + + .. versionadded:: 1.2.17 + + .. seealso:: + + :meth:`.QueryEvents.before_compile` + + :meth:`.QueryEvents.before_compile_delete` + + + """ # noqa: E501 + + def before_compile_delete( + self, query: Query[Any], delete_context: BulkDelete + ) -> None: + """Allow modifications to the :class:`_query.Query` object within + :meth:`_query.Query.delete`. + + .. deprecated:: 1.4 The :meth:`_orm.QueryEvents.before_compile_delete` + event is superseded by the much more capable + :meth:`_orm.SessionEvents.do_orm_execute` hook. + + Like the :meth:`.QueryEvents.before_compile` event, this event + should be configured with ``retval=True``, and the modified + :class:`_query.Query` object returned, as in :: + + @event.listens_for(Query, "before_compile_delete", retval=True) + def no_deleted(query, delete_context): + for desc in query.column_descriptions: + if desc["type"] is User: + entity = desc["entity"] + query = query.filter(entity.deleted == False) + return query + + :param query: a :class:`_query.Query` instance; this is also + the ``.query`` attribute of the given "delete context" + object. + + :param delete_context: a "delete context" object which is + the same kind of object as described in + :paramref:`.QueryEvents.after_bulk_delete.delete_context`. + + .. versionadded:: 1.2.17 + + .. seealso:: + + :meth:`.QueryEvents.before_compile` + + :meth:`.QueryEvents.before_compile_update` + + + """ + + @classmethod + def _listen( + cls, + event_key: _EventKey[_ET], + retval: bool = False, + bake_ok: bool = False, + **kw: Any, + ) -> None: + fn = event_key._listen_fn + + if not retval: + + def wrap(*arg: Any, **kw: Any) -> Any: + if not retval: + query = arg[0] + fn(*arg, **kw) + return query + else: + return fn(*arg, **kw) + + event_key = event_key.with_wrapper(wrap) + else: + # don't assume we can apply an attribute to the callable + def wrap(*arg: Any, **kw: Any) -> Any: + return fn(*arg, **kw) + + event_key = event_key.with_wrapper(wrap) + + wrap._bake_ok = bake_ok # type: ignore [attr-defined] + + event_key.base_listen(**kw) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/exc.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..00a16344d15ae5df22e466da5b276c747f8369e2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/exc.py @@ -0,0 +1,237 @@ +# orm/exc.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +"""SQLAlchemy ORM exceptions.""" + +from __future__ import annotations + +from typing import Any +from typing import Optional +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar + +from .util import _mapper_property_as_plain_name +from .. import exc as sa_exc +from .. import util +from ..exc import MultipleResultsFound # noqa +from ..exc import NoResultFound # noqa + +if TYPE_CHECKING: + from .interfaces import LoaderStrategy + from .interfaces import MapperProperty + from .state import InstanceState + +_T = TypeVar("_T", bound=Any) + +NO_STATE = (AttributeError, KeyError) +"""Exception types that may be raised by instrumentation implementations.""" + + +class StaleDataError(sa_exc.SQLAlchemyError): + """An operation encountered database state that is unaccounted for. + + Conditions which cause this to happen include: + + * A flush may have attempted to update or delete rows + and an unexpected number of rows were matched during + the UPDATE or DELETE statement. Note that when + version_id_col is used, rows in UPDATE or DELETE statements + are also matched against the current known version + identifier. + + * A mapped object with version_id_col was refreshed, + and the version number coming back from the database does + not match that of the object itself. + + * A object is detached from its parent object, however + the object was previously attached to a different parent + identity which was garbage collected, and a decision + cannot be made if the new parent was really the most + recent "parent". + + """ + + +ConcurrentModificationError = StaleDataError + + +class FlushError(sa_exc.SQLAlchemyError): + """A invalid condition was detected during flush().""" + + +class MappedAnnotationError(sa_exc.ArgumentError): + """Raised when ORM annotated declarative cannot interpret the + expression present inside of the :class:`.Mapped` construct. + + .. versionadded:: 2.0.40 + + """ + + +class UnmappedError(sa_exc.InvalidRequestError): + """Base for exceptions that involve expected mappings not present.""" + + +class ObjectDereferencedError(sa_exc.SQLAlchemyError): + """An operation cannot complete due to an object being garbage + collected. + + """ + + +class DetachedInstanceError(sa_exc.SQLAlchemyError): + """An attempt to access unloaded attributes on a + mapped instance that is detached.""" + + code = "bhk3" + + +class UnmappedInstanceError(UnmappedError): + """An mapping operation was requested for an unknown instance.""" + + @util.preload_module("sqlalchemy.orm.base") + def __init__(self, obj: object, msg: Optional[str] = None): + base = util.preloaded.orm_base + + if not msg: + try: + base.class_mapper(type(obj)) + name = _safe_cls_name(type(obj)) + msg = ( + "Class %r is mapped, but this instance lacks " + "instrumentation. This occurs when the instance " + "is created before sqlalchemy.orm.mapper(%s) " + "was called." % (name, name) + ) + except UnmappedClassError: + msg = f"Class '{_safe_cls_name(type(obj))}' is not mapped" + if isinstance(obj, type): + msg += ( + "; was a class (%s) supplied where an instance was " + "required?" % _safe_cls_name(obj) + ) + UnmappedError.__init__(self, msg) + + def __reduce__(self) -> Any: + return self.__class__, (None, self.args[0]) + + +class UnmappedClassError(UnmappedError): + """An mapping operation was requested for an unknown class.""" + + def __init__(self, cls: Type[_T], msg: Optional[str] = None): + if not msg: + msg = _default_unmapped(cls) + UnmappedError.__init__(self, msg) + + def __reduce__(self) -> Any: + return self.__class__, (None, self.args[0]) + + +class ObjectDeletedError(sa_exc.InvalidRequestError): + """A refresh operation failed to retrieve the database + row corresponding to an object's known primary key identity. + + A refresh operation proceeds when an expired attribute is + accessed on an object, or when :meth:`_query.Query.get` is + used to retrieve an object which is, upon retrieval, detected + as expired. A SELECT is emitted for the target row + based on primary key; if no row is returned, this + exception is raised. + + The true meaning of this exception is simply that + no row exists for the primary key identifier associated + with a persistent object. The row may have been + deleted, or in some cases the primary key updated + to a new value, outside of the ORM's management of the target + object. + + """ + + @util.preload_module("sqlalchemy.orm.base") + def __init__(self, state: InstanceState[Any], msg: Optional[str] = None): + base = util.preloaded.orm_base + + if not msg: + msg = ( + "Instance '%s' has been deleted, or its " + "row is otherwise not present." % base.state_str(state) + ) + + sa_exc.InvalidRequestError.__init__(self, msg) + + def __reduce__(self) -> Any: + return self.__class__, (None, self.args[0]) + + +class UnmappedColumnError(sa_exc.InvalidRequestError): + """Mapping operation was requested on an unknown column.""" + + +class LoaderStrategyException(sa_exc.InvalidRequestError): + """A loader strategy for an attribute does not exist.""" + + def __init__( + self, + applied_to_property_type: Type[Any], + requesting_property: MapperProperty[Any], + applies_to: Optional[Type[MapperProperty[Any]]], + actual_strategy_type: Optional[Type[LoaderStrategy]], + strategy_key: Tuple[Any, ...], + ): + if actual_strategy_type is None: + sa_exc.InvalidRequestError.__init__( + self, + "Can't find strategy %s for %s" + % (strategy_key, requesting_property), + ) + else: + assert applies_to is not None + sa_exc.InvalidRequestError.__init__( + self, + 'Can\'t apply "%s" strategy to property "%s", ' + 'which is a "%s"; this loader strategy is intended ' + 'to be used with a "%s".' + % ( + util.clsname_as_plain_name(actual_strategy_type), + requesting_property, + _mapper_property_as_plain_name(applied_to_property_type), + _mapper_property_as_plain_name(applies_to), + ), + ) + + +def _safe_cls_name(cls: Type[Any]) -> str: + cls_name: Optional[str] + try: + cls_name = ".".join((cls.__module__, cls.__name__)) + except AttributeError: + cls_name = getattr(cls, "__name__", None) + if cls_name is None: + cls_name = repr(cls) + return cls_name + + +@util.preload_module("sqlalchemy.orm.base") +def _default_unmapped(cls: Type[Any]) -> Optional[str]: + base = util.preloaded.orm_base + + try: + mappers = base.manager_of_class(cls).mappers # type: ignore + except ( + UnmappedClassError, + TypeError, + ) + NO_STATE: + mappers = {} + name = _safe_cls_name(cls) + + if not mappers: + return f"Class '{name}' is not mapped" + else: + return None diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/identity.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/identity.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3419c8c9974d8b658086e3b1ff0ff63cd0156e --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/identity.py @@ -0,0 +1,302 @@ +# orm/identity.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +from __future__ import annotations + +from typing import Any +from typing import cast +from typing import Dict +from typing import Iterable +from typing import Iterator +from typing import List +from typing import NoReturn +from typing import Optional +from typing import Set +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +import weakref + +from . import util as orm_util +from .. import exc as sa_exc + +if TYPE_CHECKING: + from ._typing import _IdentityKeyType + from .state import InstanceState + + +_T = TypeVar("_T", bound=Any) + +_O = TypeVar("_O", bound=object) + + +class IdentityMap: + _wr: weakref.ref[IdentityMap] + + _dict: Dict[_IdentityKeyType[Any], Any] + _modified: Set[InstanceState[Any]] + + def __init__(self) -> None: + self._dict = {} + self._modified = set() + self._wr = weakref.ref(self) + + def _kill(self) -> None: + self._add_unpresent = _killed # type: ignore + + def all_states(self) -> List[InstanceState[Any]]: + raise NotImplementedError() + + def contains_state(self, state: InstanceState[Any]) -> bool: + raise NotImplementedError() + + def __contains__(self, key: _IdentityKeyType[Any]) -> bool: + raise NotImplementedError() + + def safe_discard(self, state: InstanceState[Any]) -> None: + raise NotImplementedError() + + def __getitem__(self, key: _IdentityKeyType[_O]) -> _O: + raise NotImplementedError() + + def get( + self, key: _IdentityKeyType[_O], default: Optional[_O] = None + ) -> Optional[_O]: + raise NotImplementedError() + + def fast_get_state( + self, key: _IdentityKeyType[_O] + ) -> Optional[InstanceState[_O]]: + raise NotImplementedError() + + def keys(self) -> Iterable[_IdentityKeyType[Any]]: + return self._dict.keys() + + def values(self) -> Iterable[object]: + raise NotImplementedError() + + def replace(self, state: InstanceState[_O]) -> Optional[InstanceState[_O]]: + raise NotImplementedError() + + def add(self, state: InstanceState[Any]) -> bool: + raise NotImplementedError() + + def _fast_discard(self, state: InstanceState[Any]) -> None: + raise NotImplementedError() + + def _add_unpresent( + self, state: InstanceState[Any], key: _IdentityKeyType[Any] + ) -> None: + """optional inlined form of add() which can assume item isn't present + in the map""" + self.add(state) + + def _manage_incoming_state(self, state: InstanceState[Any]) -> None: + state._instance_dict = self._wr + + if state.modified: + self._modified.add(state) + + def _manage_removed_state(self, state: InstanceState[Any]) -> None: + del state._instance_dict + if state.modified: + self._modified.discard(state) + + def _dirty_states(self) -> Set[InstanceState[Any]]: + return self._modified + + def check_modified(self) -> bool: + """return True if any InstanceStates present have been marked + as 'modified'. + + """ + return bool(self._modified) + + def has_key(self, key: _IdentityKeyType[Any]) -> bool: + return key in self + + def __len__(self) -> int: + return len(self._dict) + + +class WeakInstanceDict(IdentityMap): + _dict: Dict[_IdentityKeyType[Any], InstanceState[Any]] + + def __getitem__(self, key: _IdentityKeyType[_O]) -> _O: + state = cast("InstanceState[_O]", self._dict[key]) + o = state.obj() + if o is None: + raise KeyError(key) + return o + + def __contains__(self, key: _IdentityKeyType[Any]) -> bool: + try: + if key in self._dict: + state = self._dict[key] + o = state.obj() + else: + return False + except KeyError: + return False + else: + return o is not None + + def contains_state(self, state: InstanceState[Any]) -> bool: + if state.key in self._dict: + if TYPE_CHECKING: + assert state.key is not None + try: + return self._dict[state.key] is state + except KeyError: + return False + else: + return False + + def replace( + self, state: InstanceState[Any] + ) -> Optional[InstanceState[Any]]: + assert state.key is not None + if state.key in self._dict: + try: + existing = existing_non_none = self._dict[state.key] + except KeyError: + # catch gc removed the key after we just checked for it + existing = None + else: + if existing_non_none is not state: + self._manage_removed_state(existing_non_none) + else: + return None + else: + existing = None + + self._dict[state.key] = state + self._manage_incoming_state(state) + return existing + + def add(self, state: InstanceState[Any]) -> bool: + key = state.key + assert key is not None + # inline of self.__contains__ + if key in self._dict: + try: + existing_state = self._dict[key] + except KeyError: + # catch gc removed the key after we just checked for it + pass + else: + if existing_state is not state: + o = existing_state.obj() + if o is not None: + raise sa_exc.InvalidRequestError( + "Can't attach instance " + "%s; another instance with key %s is already " + "present in this session." + % (orm_util.state_str(state), state.key) + ) + else: + return False + self._dict[key] = state + self._manage_incoming_state(state) + return True + + def _add_unpresent( + self, state: InstanceState[Any], key: _IdentityKeyType[Any] + ) -> None: + # inlined form of add() called by loading.py + self._dict[key] = state + state._instance_dict = self._wr + + def fast_get_state( + self, key: _IdentityKeyType[_O] + ) -> Optional[InstanceState[_O]]: + return self._dict.get(key) + + def get( + self, key: _IdentityKeyType[_O], default: Optional[_O] = None + ) -> Optional[_O]: + if key not in self._dict: + return default + try: + state = cast("InstanceState[_O]", self._dict[key]) + except KeyError: + # catch gc removed the key after we just checked for it + return default + else: + o = state.obj() + if o is None: + return default + return o + + def items(self) -> List[Tuple[_IdentityKeyType[Any], InstanceState[Any]]]: + values = self.all_states() + result = [] + for state in values: + value = state.obj() + key = state.key + assert key is not None + if value is not None: + result.append((key, value)) + return result + + def values(self) -> List[object]: + values = self.all_states() + result = [] + for state in values: + value = state.obj() + if value is not None: + result.append(value) + + return result + + def __iter__(self) -> Iterator[_IdentityKeyType[Any]]: + return iter(self.keys()) + + def all_states(self) -> List[InstanceState[Any]]: + return list(self._dict.values()) + + def _fast_discard(self, state: InstanceState[Any]) -> None: + # used by InstanceState for state being + # GC'ed, inlines _managed_removed_state + key = state.key + assert key is not None + try: + st = self._dict[key] + except KeyError: + # catch gc removed the key after we just checked for it + pass + else: + if st is state: + self._dict.pop(key, None) + + def discard(self, state: InstanceState[Any]) -> None: + self.safe_discard(state) + + def safe_discard(self, state: InstanceState[Any]) -> None: + key = state.key + if key in self._dict: + assert key is not None + try: + st = self._dict[key] + except KeyError: + # catch gc removed the key after we just checked for it + pass + else: + if st is state: + self._dict.pop(key, None) + self._manage_removed_state(state) + + +def _killed(state: InstanceState[Any], key: _IdentityKeyType[Any]) -> NoReturn: + # external function to avoid creating cycles when assigned to + # the IdentityMap + raise sa_exc.InvalidRequestError( + "Object %s cannot be converted to 'persistent' state, as this " + "identity map is no longer valid. Has the owning Session " + "been closed?" % orm_util.state_str(state), + code="lkrp", + ) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/instrumentation.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..f68c9739c51e22b0a0a2f1b8b4485ea6161872ec --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/instrumentation.py @@ -0,0 +1,754 @@ +# orm/instrumentation.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: allow-untyped-defs, allow-untyped-calls + +"""Defines SQLAlchemy's system of class instrumentation. + +This module is usually not directly visible to user applications, but +defines a large part of the ORM's interactivity. + +instrumentation.py deals with registration of end-user classes +for state tracking. It interacts closely with state.py +and attributes.py which establish per-instance and per-class-attribute +instrumentation, respectively. + +The class instrumentation system can be customized on a per-class +or global basis using the :mod:`sqlalchemy.ext.instrumentation` +module, which provides the means to build and specify +alternate instrumentation forms. + +.. versionchanged: 0.8 + The instrumentation extension system was moved out of the + ORM and into the external :mod:`sqlalchemy.ext.instrumentation` + package. When that package is imported, it installs + itself within sqlalchemy.orm so that its more comprehensive + resolution mechanics take effect. + +""" + + +from __future__ import annotations + +from typing import Any +from typing import Callable +from typing import cast +from typing import Collection +from typing import Dict +from typing import Generic +from typing import Iterable +from typing import List +from typing import Optional +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union +import weakref + +from . import base +from . import collections +from . import exc +from . import interfaces +from . import state +from ._typing import _O +from .attributes import _is_collection_attribute_impl +from .. import util +from ..event import EventTarget +from ..util import HasMemoized +from ..util.typing import Literal +from ..util.typing import Protocol + +if TYPE_CHECKING: + from ._typing import _RegistryType + from .attributes import AttributeImpl + from .attributes import QueryableAttribute + from .collections import _AdaptedCollectionProtocol + from .collections import _CollectionFactoryType + from .decl_base import _MapperConfig + from .events import InstanceEvents + from .mapper import Mapper + from .state import InstanceState + from ..event import dispatcher + +_T = TypeVar("_T", bound=Any) +DEL_ATTR = util.symbol("DEL_ATTR") + + +class _ExpiredAttributeLoaderProto(Protocol): + def __call__( + self, + state: state.InstanceState[Any], + toload: Set[str], + passive: base.PassiveFlag, + ) -> None: ... + + +class _ManagerFactory(Protocol): + def __call__(self, class_: Type[_O]) -> ClassManager[_O]: ... + + +class ClassManager( + HasMemoized, + Dict[str, "QueryableAttribute[Any]"], + Generic[_O], + EventTarget, +): + """Tracks state information at the class level.""" + + dispatch: dispatcher[ClassManager[_O]] + + MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR + STATE_ATTR = base.DEFAULT_STATE_ATTR + + _state_setter = staticmethod(util.attrsetter(STATE_ATTR)) + + expired_attribute_loader: _ExpiredAttributeLoaderProto + "previously known as deferred_scalar_loader" + + init_method: Optional[Callable[..., None]] + original_init: Optional[Callable[..., None]] = None + + factory: Optional[_ManagerFactory] + + declarative_scan: Optional[weakref.ref[_MapperConfig]] = None + + registry: _RegistryType + + if not TYPE_CHECKING: + # starts as None during setup + registry = None + + class_: Type[_O] + + _bases: List[ClassManager[Any]] + + @property + @util.deprecated( + "1.4", + message="The ClassManager.deferred_scalar_loader attribute is now " + "named expired_attribute_loader", + ) + def deferred_scalar_loader(self): + return self.expired_attribute_loader + + @deferred_scalar_loader.setter + @util.deprecated( + "1.4", + message="The ClassManager.deferred_scalar_loader attribute is now " + "named expired_attribute_loader", + ) + def deferred_scalar_loader(self, obj): + self.expired_attribute_loader = obj + + def __init__(self, class_): + self.class_ = class_ + self.info = {} + self.new_init = None + self.local_attrs = {} + self.originals = {} + self._finalized = False + self.factory = None + self.init_method = None + + self._bases = [ + mgr + for mgr in cast( + "List[Optional[ClassManager[Any]]]", + [ + opt_manager_of_class(base) + for base in self.class_.__bases__ + if isinstance(base, type) + ], + ) + if mgr is not None + ] + + for base_ in self._bases: + self.update(base_) + + cast( + "InstanceEvents", self.dispatch._events + )._new_classmanager_instance(class_, self) + + for basecls in class_.__mro__: + mgr = opt_manager_of_class(basecls) + if mgr is not None: + self.dispatch._update(mgr.dispatch) + + self.manage() + + if "__del__" in class_.__dict__: + util.warn( + "__del__() method on class %s will " + "cause unreachable cycles and memory leaks, " + "as SQLAlchemy instrumentation often creates " + "reference cycles. Please remove this method." % class_ + ) + + def _update_state( + self, + finalize: bool = False, + mapper: Optional[Mapper[_O]] = None, + registry: Optional[_RegistryType] = None, + declarative_scan: Optional[_MapperConfig] = None, + expired_attribute_loader: Optional[ + _ExpiredAttributeLoaderProto + ] = None, + init_method: Optional[Callable[..., None]] = None, + ) -> None: + if mapper: + self.mapper = mapper # + if registry: + registry._add_manager(self) + if declarative_scan: + self.declarative_scan = weakref.ref(declarative_scan) + if expired_attribute_loader: + self.expired_attribute_loader = expired_attribute_loader + + if init_method: + assert not self._finalized, ( + "class is already instrumented, " + "init_method %s can't be applied" % init_method + ) + self.init_method = init_method + + if not self._finalized: + self.original_init = ( + self.init_method + if self.init_method is not None + and self.class_.__init__ is object.__init__ + else self.class_.__init__ + ) + + if finalize and not self._finalized: + self._finalize() + + def _finalize(self) -> None: + if self._finalized: + return + self._finalized = True + + self._instrument_init() + + _instrumentation_factory.dispatch.class_instrument(self.class_) + + def __hash__(self) -> int: # type: ignore[override] + return id(self) + + def __eq__(self, other: Any) -> bool: + return other is self + + @property + def is_mapped(self) -> bool: + return "mapper" in self.__dict__ + + @HasMemoized.memoized_attribute + def _all_key_set(self): + return frozenset(self) + + @HasMemoized.memoized_attribute + def _collection_impl_keys(self): + return frozenset( + [attr.key for attr in self.values() if attr.impl.collection] + ) + + @HasMemoized.memoized_attribute + def _scalar_loader_impls(self): + return frozenset( + [ + attr.impl + for attr in self.values() + if attr.impl.accepts_scalar_loader + ] + ) + + @HasMemoized.memoized_attribute + def _loader_impls(self): + return frozenset([attr.impl for attr in self.values()]) + + @util.memoized_property + def mapper(self) -> Mapper[_O]: + # raises unless self.mapper has been assigned + raise exc.UnmappedClassError(self.class_) + + def _all_sqla_attributes(self, exclude=None): + """return an iterator of all classbound attributes that are + implement :class:`.InspectionAttr`. + + This includes :class:`.QueryableAttribute` as well as extension + types such as :class:`.hybrid_property` and + :class:`.AssociationProxy`. + + """ + + found: Dict[str, Any] = {} + + # constraints: + # 1. yield keys in cls.__dict__ order + # 2. if a subclass has the same key as a superclass, include that + # key as part of the ordering of the superclass, because an + # overridden key is usually installed by the mapper which is going + # on a different ordering + # 3. don't use getattr() as this fires off descriptors + + for supercls in self.class_.__mro__[0:-1]: + inherits = supercls.__mro__[1] + for key in supercls.__dict__: + found.setdefault(key, supercls) + if key in inherits.__dict__: + continue + val = found[key].__dict__[key] + if ( + isinstance(val, interfaces.InspectionAttr) + and val.is_attribute + ): + yield key, val + + def _get_class_attr_mro(self, key, default=None): + """return an attribute on the class without tripping it.""" + + for supercls in self.class_.__mro__: + if key in supercls.__dict__: + return supercls.__dict__[key] + else: + return default + + def _attr_has_impl(self, key: str) -> bool: + """Return True if the given attribute is fully initialized. + + i.e. has an impl. + """ + + return key in self and self[key].impl is not None + + def _subclass_manager(self, cls: Type[_T]) -> ClassManager[_T]: + """Create a new ClassManager for a subclass of this ClassManager's + class. + + This is called automatically when attributes are instrumented so that + the attributes can be propagated to subclasses against their own + class-local manager, without the need for mappers etc. to have already + pre-configured managers for the full class hierarchy. Mappers + can post-configure the auto-generated ClassManager when needed. + + """ + return register_class(cls, finalize=False) + + def _instrument_init(self): + self.new_init = _generate_init(self.class_, self, self.original_init) + self.install_member("__init__", self.new_init) + + @util.memoized_property + def _state_constructor(self) -> Type[state.InstanceState[_O]]: + self.dispatch.first_init(self, self.class_) + return state.InstanceState + + def manage(self): + """Mark this instance as the manager for its class.""" + + setattr(self.class_, self.MANAGER_ATTR, self) + + @util.hybridmethod + def manager_getter(self): + return _default_manager_getter + + @util.hybridmethod + def state_getter(self): + """Return a (instance) -> InstanceState callable. + + "state getter" callables should raise either KeyError or + AttributeError if no InstanceState could be found for the + instance. + """ + + return _default_state_getter + + @util.hybridmethod + def dict_getter(self): + return _default_dict_getter + + def instrument_attribute( + self, + key: str, + inst: QueryableAttribute[Any], + propagated: bool = False, + ) -> None: + if propagated: + if key in self.local_attrs: + return # don't override local attr with inherited attr + else: + self.local_attrs[key] = inst + self.install_descriptor(key, inst) + self._reset_memoizations() + self[key] = inst + + for cls in self.class_.__subclasses__(): + manager = self._subclass_manager(cls) + manager.instrument_attribute(key, inst, True) + + def subclass_managers(self, recursive): + for cls in self.class_.__subclasses__(): + mgr = opt_manager_of_class(cls) + if mgr is not None and mgr is not self: + yield mgr + if recursive: + yield from mgr.subclass_managers(True) + + def post_configure_attribute(self, key): + _instrumentation_factory.dispatch.attribute_instrument( + self.class_, key, self[key] + ) + + def uninstrument_attribute(self, key, propagated=False): + if key not in self: + return + if propagated: + if key in self.local_attrs: + return # don't get rid of local attr + else: + del self.local_attrs[key] + self.uninstall_descriptor(key) + self._reset_memoizations() + del self[key] + for cls in self.class_.__subclasses__(): + manager = opt_manager_of_class(cls) + if manager: + manager.uninstrument_attribute(key, True) + + def unregister(self) -> None: + """remove all instrumentation established by this ClassManager.""" + + for key in list(self.originals): + self.uninstall_member(key) + + self.mapper = None + self.dispatch = None # type: ignore + self.new_init = None + self.info.clear() + + for key in list(self): + if key in self.local_attrs: + self.uninstrument_attribute(key) + + if self.MANAGER_ATTR in self.class_.__dict__: + delattr(self.class_, self.MANAGER_ATTR) + + def install_descriptor( + self, key: str, inst: QueryableAttribute[Any] + ) -> None: + if key in (self.STATE_ATTR, self.MANAGER_ATTR): + raise KeyError( + "%r: requested attribute name conflicts with " + "instrumentation attribute of the same name." % key + ) + setattr(self.class_, key, inst) + + def uninstall_descriptor(self, key: str) -> None: + delattr(self.class_, key) + + def install_member(self, key: str, implementation: Any) -> None: + if key in (self.STATE_ATTR, self.MANAGER_ATTR): + raise KeyError( + "%r: requested attribute name conflicts with " + "instrumentation attribute of the same name." % key + ) + self.originals.setdefault(key, self.class_.__dict__.get(key, DEL_ATTR)) + setattr(self.class_, key, implementation) + + def uninstall_member(self, key: str) -> None: + original = self.originals.pop(key, None) + if original is not DEL_ATTR: + setattr(self.class_, key, original) + else: + delattr(self.class_, key) + + def instrument_collection_class( + self, key: str, collection_class: Type[Collection[Any]] + ) -> _CollectionFactoryType: + return collections.prepare_instrumentation(collection_class) + + def initialize_collection( + self, + key: str, + state: InstanceState[_O], + factory: _CollectionFactoryType, + ) -> Tuple[collections.CollectionAdapter, _AdaptedCollectionProtocol]: + user_data = factory() + impl = self.get_impl(key) + assert _is_collection_attribute_impl(impl) + adapter = collections.CollectionAdapter(impl, state, user_data) + return adapter, user_data + + def is_instrumented(self, key: str, search: bool = False) -> bool: + if search: + return key in self + else: + return key in self.local_attrs + + def get_impl(self, key: str) -> AttributeImpl: + return self[key].impl + + @property + def attributes(self) -> Iterable[Any]: + return iter(self.values()) + + # InstanceState management + + def new_instance(self, state: Optional[InstanceState[_O]] = None) -> _O: + # here, we would prefer _O to be bound to "object" + # so that mypy sees that __new__ is present. currently + # it's bound to Any as there were other problems not having + # it that way but these can be revisited + instance = self.class_.__new__(self.class_) + if state is None: + state = self._state_constructor(instance, self) + self._state_setter(instance, state) + return instance + + def setup_instance( + self, instance: _O, state: Optional[InstanceState[_O]] = None + ) -> None: + if state is None: + state = self._state_constructor(instance, self) + self._state_setter(instance, state) + + def teardown_instance(self, instance: _O) -> None: + delattr(instance, self.STATE_ATTR) + + def _serialize( + self, state: InstanceState[_O], state_dict: Dict[str, Any] + ) -> _SerializeManager: + return _SerializeManager(state, state_dict) + + def _new_state_if_none( + self, instance: _O + ) -> Union[Literal[False], InstanceState[_O]]: + """Install a default InstanceState if none is present. + + A private convenience method used by the __init__ decorator. + + """ + if hasattr(instance, self.STATE_ATTR): + return False + elif self.class_ is not instance.__class__ and self.is_mapped: + # this will create a new ClassManager for the + # subclass, without a mapper. This is likely a + # user error situation but allow the object + # to be constructed, so that it is usable + # in a non-ORM context at least. + return self._subclass_manager( + instance.__class__ + )._new_state_if_none(instance) + else: + state = self._state_constructor(instance, self) + self._state_setter(instance, state) + return state + + def has_state(self, instance: _O) -> bool: + return hasattr(instance, self.STATE_ATTR) + + def has_parent( + self, state: InstanceState[_O], key: str, optimistic: bool = False + ) -> bool: + """TODO""" + return self.get_impl(key).hasparent(state, optimistic=optimistic) + + def __bool__(self) -> bool: + """All ClassManagers are non-zero regardless of attribute state.""" + return True + + def __repr__(self) -> str: + return "<%s of %r at %x>" % ( + self.__class__.__name__, + self.class_, + id(self), + ) + + +class _SerializeManager: + """Provide serialization of a :class:`.ClassManager`. + + The :class:`.InstanceState` uses ``__init__()`` on serialize + and ``__call__()`` on deserialize. + + """ + + def __init__(self, state: state.InstanceState[Any], d: Dict[str, Any]): + self.class_ = state.class_ + manager = state.manager + manager.dispatch.pickle(state, d) + + def __call__(self, state, inst, state_dict): + state.manager = manager = opt_manager_of_class(self.class_) + if manager is None: + raise exc.UnmappedInstanceError( + inst, + "Cannot deserialize object of type %r - " + "no mapper() has " + "been configured for this class within the current " + "Python process!" % self.class_, + ) + elif manager.is_mapped and not manager.mapper.configured: + manager.mapper._check_configure() + + # setup _sa_instance_state ahead of time so that + # unpickle events can access the object normally. + # see [ticket:2362] + if inst is not None: + manager.setup_instance(inst, state) + manager.dispatch.unpickle(state, state_dict) + + +class InstrumentationFactory(EventTarget): + """Factory for new ClassManager instances.""" + + dispatch: dispatcher[InstrumentationFactory] + + def create_manager_for_cls(self, class_: Type[_O]) -> ClassManager[_O]: + assert class_ is not None + assert opt_manager_of_class(class_) is None + + # give a more complicated subclass + # a chance to do what it wants here + manager, factory = self._locate_extended_factory(class_) + + if factory is None: + factory = ClassManager + manager = ClassManager(class_) + else: + assert manager is not None + + self._check_conflicts(class_, factory) + + manager.factory = factory + + return manager + + def _locate_extended_factory( + self, class_: Type[_O] + ) -> Tuple[Optional[ClassManager[_O]], Optional[_ManagerFactory]]: + """Overridden by a subclass to do an extended lookup.""" + return None, None + + def _check_conflicts( + self, class_: Type[_O], factory: Callable[[Type[_O]], ClassManager[_O]] + ) -> None: + """Overridden by a subclass to test for conflicting factories.""" + + def unregister(self, class_: Type[_O]) -> None: + manager = manager_of_class(class_) + manager.unregister() + self.dispatch.class_uninstrument(class_) + + +# this attribute is replaced by sqlalchemy.ext.instrumentation +# when imported. +_instrumentation_factory = InstrumentationFactory() + +# these attributes are replaced by sqlalchemy.ext.instrumentation +# when a non-standard InstrumentationManager class is first +# used to instrument a class. +instance_state = _default_state_getter = base.instance_state + +instance_dict = _default_dict_getter = base.instance_dict + +manager_of_class = _default_manager_getter = base.manager_of_class +opt_manager_of_class = _default_opt_manager_getter = base.opt_manager_of_class + + +def register_class( + class_: Type[_O], + finalize: bool = True, + mapper: Optional[Mapper[_O]] = None, + registry: Optional[_RegistryType] = None, + declarative_scan: Optional[_MapperConfig] = None, + expired_attribute_loader: Optional[_ExpiredAttributeLoaderProto] = None, + init_method: Optional[Callable[..., None]] = None, +) -> ClassManager[_O]: + """Register class instrumentation. + + Returns the existing or newly created class manager. + + """ + + manager = opt_manager_of_class(class_) + if manager is None: + manager = _instrumentation_factory.create_manager_for_cls(class_) + manager._update_state( + mapper=mapper, + registry=registry, + declarative_scan=declarative_scan, + expired_attribute_loader=expired_attribute_loader, + init_method=init_method, + finalize=finalize, + ) + + return manager + + +def unregister_class(class_): + """Unregister class instrumentation.""" + + _instrumentation_factory.unregister(class_) + + +def is_instrumented(instance, key): + """Return True if the given attribute on the given instance is + instrumented by the attributes package. + + This function may be used regardless of instrumentation + applied directly to the class, i.e. no descriptors are required. + + """ + return manager_of_class(instance.__class__).is_instrumented( + key, search=True + ) + + +def _generate_init(class_, class_manager, original_init): + """Build an __init__ decorator that triggers ClassManager events.""" + + # TODO: we should use the ClassManager's notion of the + # original '__init__' method, once ClassManager is fixed + # to always reference that. + + if original_init is None: + original_init = class_.__init__ + + # Go through some effort here and don't change the user's __init__ + # calling signature, including the unlikely case that it has + # a return value. + # FIXME: need to juggle local names to avoid constructor argument + # clashes. + func_body = """\ +def __init__(%(apply_pos)s): + new_state = class_manager._new_state_if_none(%(self_arg)s) + if new_state: + return new_state._initialize_instance(%(apply_kw)s) + else: + return original_init(%(apply_kw)s) +""" + func_vars = util.format_argspec_init(original_init, grouped=False) + func_text = func_body % func_vars + + func_defaults = getattr(original_init, "__defaults__", None) + func_kw_defaults = getattr(original_init, "__kwdefaults__", None) + + env = locals().copy() + env["__name__"] = __name__ + exec(func_text, env) + __init__ = env["__init__"] + __init__.__doc__ = original_init.__doc__ + __init__._sa_original_init = original_init + + if func_defaults: + __init__.__defaults__ = func_defaults + if func_kw_defaults: + __init__.__kwdefaults__ = func_kw_defaults + + return __init__ diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/interfaces.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..f3346a04eea0d50a9dcfac7751be2e3b65d9c28a --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/interfaces.py @@ -0,0 +1,1496 @@ +# orm/interfaces.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php + +""" + +Contains various base classes used throughout the ORM. + +Defines some key base classes prominent within the internals. + +This module and the classes within are mostly private, though some attributes +are exposed when inspecting mappings. + +""" + +from __future__ import annotations + +import collections +import dataclasses +import typing +from typing import Any +from typing import Callable +from typing import cast +from typing import ClassVar +from typing import Dict +from typing import Generic +from typing import Iterator +from typing import List +from typing import Mapping +from typing import NamedTuple +from typing import NoReturn +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Type +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import exc as orm_exc +from . import path_registry +from .base import _MappedAttribute as _MappedAttribute +from .base import EXT_CONTINUE as EXT_CONTINUE # noqa: F401 +from .base import EXT_SKIP as EXT_SKIP # noqa: F401 +from .base import EXT_STOP as EXT_STOP # noqa: F401 +from .base import InspectionAttr as InspectionAttr # noqa: F401 +from .base import InspectionAttrInfo as InspectionAttrInfo +from .base import MANYTOMANY as MANYTOMANY # noqa: F401 +from .base import MANYTOONE as MANYTOONE # noqa: F401 +from .base import NO_KEY as NO_KEY # noqa: F401 +from .base import NO_VALUE as NO_VALUE # noqa: F401 +from .base import NotExtension as NotExtension # noqa: F401 +from .base import ONETOMANY as ONETOMANY # noqa: F401 +from .base import RelationshipDirection as RelationshipDirection # noqa: F401 +from .base import SQLORMOperations +from .. import ColumnElement +from .. import exc as sa_exc +from .. import inspection +from .. import util +from ..sql import operators +from ..sql import roles +from ..sql import visitors +from ..sql.base import _NoArg +from ..sql.base import ExecutableOption +from ..sql.cache_key import HasCacheKey +from ..sql.operators import ColumnOperators +from ..sql.schema import Column +from ..sql.type_api import TypeEngine +from ..util import warn_deprecated +from ..util.typing import RODescriptorReference +from ..util.typing import TypedDict + +if typing.TYPE_CHECKING: + from ._typing import _EntityType + from ._typing import _IdentityKeyType + from ._typing import _InstanceDict + from ._typing import _InternalEntityType + from ._typing import _ORMAdapterProto + from .attributes import InstrumentedAttribute + from .base import Mapped + from .context import _MapperEntity + from .context import ORMCompileState + from .context import QueryContext + from .decl_api import RegistryType + from .decl_base import _ClassScanMapperConfig + from .loading import _PopulatorDict + from .mapper import Mapper + from .path_registry import AbstractEntityRegistry + from .query import Query + from .session import Session + from .state import InstanceState + from .strategy_options import _LoadElement + from .util import AliasedInsp + from .util import ORMAdapter + from ..engine.result import Result + from ..sql._typing import _ColumnExpressionArgument + from ..sql._typing import _ColumnsClauseArgument + from ..sql._typing import _DMLColumnArgument + from ..sql._typing import _InfoType + from ..sql.operators import OperatorType + from ..sql.visitors import _TraverseInternalsType + from ..util.typing import _AnnotationScanType + +_StrategyKey = Tuple[Any, ...] + +_T = TypeVar("_T", bound=Any) +_T_co = TypeVar("_T_co", bound=Any, covariant=True) + +_TLS = TypeVar("_TLS", bound="Type[LoaderStrategy]") + + +class ORMStatementRole(roles.StatementRole): + __slots__ = () + _role_name = ( + "Executable SQL or text() construct, including ORM aware objects" + ) + + +class ORMColumnsClauseRole( + roles.ColumnsClauseRole, roles.TypedColumnsClauseRole[_T] +): + __slots__ = () + _role_name = "ORM mapped entity, aliased entity, or Column expression" + + +class ORMEntityColumnsClauseRole(ORMColumnsClauseRole[_T]): + __slots__ = () + _role_name = "ORM mapped or aliased entity" + + +class ORMFromClauseRole(roles.StrictFromClauseRole): + __slots__ = () + _role_name = "ORM mapped entity, aliased entity, or FROM expression" + + +class ORMColumnDescription(TypedDict): + name: str + # TODO: add python_type and sql_type here; combining them + # into "type" is a bad idea + type: Union[Type[Any], TypeEngine[Any]] + aliased: bool + expr: _ColumnsClauseArgument[Any] + entity: Optional[_ColumnsClauseArgument[Any]] + + +class _IntrospectsAnnotations: + __slots__ = () + + @classmethod + def _mapper_property_name(cls) -> str: + return cls.__name__ + + def found_in_pep593_annotated(self) -> Any: + """return a copy of this object to use in declarative when the + object is found inside of an Annotated object.""" + + raise NotImplementedError( + f"Use of the {self._mapper_property_name()!r} " + "construct inside of an Annotated object is not yet supported." + ) + + def declarative_scan( + self, + decl_scan: _ClassScanMapperConfig, + registry: RegistryType, + cls: Type[Any], + originating_module: Optional[str], + key: str, + mapped_container: Optional[Type[Mapped[Any]]], + annotation: Optional[_AnnotationScanType], + extracted_mapped_annotation: Optional[_AnnotationScanType], + is_dataclass_field: bool, + ) -> None: + """Perform class-specific initialization at early declarative scanning + time. + + .. versionadded:: 2.0 + + """ + + def _raise_for_required(self, key: str, cls: Type[Any]) -> NoReturn: + raise sa_exc.ArgumentError( + f"Python typing annotation is required for attribute " + f'"{cls.__name__}.{key}" when primary argument(s) for ' + f'"{self._mapper_property_name()}" ' + "construct are None or not present" + ) + + +class _AttributeOptions(NamedTuple): + """define Python-local attribute behavior options common to all + :class:`.MapperProperty` objects. + + Currently this includes dataclass-generation arguments. + + .. versionadded:: 2.0 + + """ + + dataclasses_init: Union[_NoArg, bool] + dataclasses_repr: Union[_NoArg, bool] + dataclasses_default: Union[_NoArg, Any] + dataclasses_default_factory: Union[_NoArg, Callable[[], Any]] + dataclasses_compare: Union[_NoArg, bool] + dataclasses_kw_only: Union[_NoArg, bool] + dataclasses_hash: Union[_NoArg, bool, None] + dataclasses_dataclass_metadata: Union[_NoArg, Mapping[Any, Any], None] + + def _as_dataclass_field(self, key: str) -> Any: + """Return a ``dataclasses.Field`` object given these arguments.""" + + kw: Dict[str, Any] = {} + if self.dataclasses_default_factory is not _NoArg.NO_ARG: + kw["default_factory"] = self.dataclasses_default_factory + if self.dataclasses_default is not _NoArg.NO_ARG: + kw["default"] = self.dataclasses_default + if self.dataclasses_init is not _NoArg.NO_ARG: + kw["init"] = self.dataclasses_init + if self.dataclasses_repr is not _NoArg.NO_ARG: + kw["repr"] = self.dataclasses_repr + if self.dataclasses_compare is not _NoArg.NO_ARG: + kw["compare"] = self.dataclasses_compare + if self.dataclasses_kw_only is not _NoArg.NO_ARG: + kw["kw_only"] = self.dataclasses_kw_only + if self.dataclasses_hash is not _NoArg.NO_ARG: + kw["hash"] = self.dataclasses_hash + if self.dataclasses_dataclass_metadata is not _NoArg.NO_ARG: + kw["metadata"] = self.dataclasses_dataclass_metadata + + if "default" in kw and callable(kw["default"]): + # callable defaults are ambiguous. deprecate them in favour of + # insert_default or default_factory. #9936 + warn_deprecated( + f"Callable object passed to the ``default`` parameter for " + f"attribute {key!r} in a ORM-mapped Dataclasses context is " + "ambiguous, " + "and this use will raise an error in a future release. " + "If this callable is intended to produce Core level INSERT " + "default values for an underlying ``Column``, use " + "the ``mapped_column.insert_default`` parameter instead. " + "To establish this callable as providing a default value " + "for instances of the dataclass itself, use the " + "``default_factory`` dataclasses parameter.", + "2.0", + ) + + if ( + "init" in kw + and not kw["init"] + and "default" in kw + and not callable(kw["default"]) # ignore callable defaults. #9936 + and "default_factory" not in kw # illegal but let dc.field raise + ): + # fix for #9879 + default = kw.pop("default") + kw["default_factory"] = lambda: default + + return dataclasses.field(**kw) + + @classmethod + def _get_arguments_for_make_dataclass( + cls, + key: str, + annotation: _AnnotationScanType, + mapped_container: Optional[Any], + elem: Any, + ) -> Union[ + Tuple[str, _AnnotationScanType], + Tuple[str, _AnnotationScanType, dataclasses.Field[Any]], + ]: + """given attribute key, annotation, and value from a class, return + the argument tuple we would pass to dataclasses.make_dataclass() + for this attribute. + + """ + if isinstance(elem, _DCAttributeOptions): + dc_field = elem._attribute_options._as_dataclass_field(key) + + return (key, annotation, dc_field) + elif elem is not _NoArg.NO_ARG: + # why is typing not erroring on this? + return (key, annotation, elem) + elif mapped_container is not None: + # it's Mapped[], but there's no "element", which means declarative + # did not actually do anything for this field. this shouldn't + # happen. + # previously, this would occur because _scan_attributes would + # skip a field that's on an already mapped superclass, but it + # would still include it in the annotations, leading + # to issue #8718 + + assert False, "Mapped[] received without a mapping declaration" + + else: + # plain dataclass field, not mapped. Is only possible + # if __allow_unmapped__ is set up. I can see this mode causing + # problems... + return (key, annotation) + + +_DEFAULT_ATTRIBUTE_OPTIONS = _AttributeOptions( + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, +) + +_DEFAULT_READONLY_ATTRIBUTE_OPTIONS = _AttributeOptions( + False, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, + _NoArg.NO_ARG, +) + + +class _DCAttributeOptions: + """mixin for descriptors or configurational objects that include dataclass + field options. + + This includes :class:`.MapperProperty`, :class:`._MapsColumn` within + the ORM, but also includes :class:`.AssociationProxy` within ext. + Can in theory be used for other descriptors that serve a similar role + as association proxy. (*maybe* hybrids, not sure yet.) + + """ + + __slots__ = () + + _attribute_options: _AttributeOptions + """behavioral options for ORM-enabled Python attributes + + .. versionadded:: 2.0 + + """ + + _has_dataclass_arguments: bool + + +class _MapsColumns(_DCAttributeOptions, _MappedAttribute[_T]): + """interface for declarative-capable construct that delivers one or more + Column objects to the declarative process to be part of a Table. + """ + + __slots__ = () + + @property + def mapper_property_to_assign(self) -> Optional[MapperProperty[_T]]: + """return a MapperProperty to be assigned to the declarative mapping""" + raise NotImplementedError() + + @property + def columns_to_assign(self) -> List[Tuple[Column[_T], int]]: + """A list of Column objects that should be declaratively added to the + new Table object. + + """ + raise NotImplementedError() + + +# NOTE: MapperProperty needs to extend _MappedAttribute so that declarative +# typing works, i.e. "Mapped[A] = relationship()". This introduces an +# inconvenience which is that all the MapperProperty objects are treated +# as descriptors by typing tools, which are misled by this as assignment / +# access to a descriptor attribute wants to move through __get__. +# Therefore, references to MapperProperty as an instance variable, such +# as in PropComparator, may have some special typing workarounds such as the +# use of sqlalchemy.util.typing.DescriptorReference to avoid mis-interpretation +# by typing tools +@inspection._self_inspects +class MapperProperty( + HasCacheKey, + _DCAttributeOptions, + _MappedAttribute[_T], + InspectionAttrInfo, + util.MemoizedSlots, +): + """Represent a particular class attribute mapped by :class:`_orm.Mapper`. + + The most common occurrences of :class:`.MapperProperty` are the + mapped :class:`_schema.Column`, which is represented in a mapping as + an instance of :class:`.ColumnProperty`, + and a reference to another class produced by :func:`_orm.relationship`, + represented in the mapping as an instance of + :class:`.Relationship`. + + """ + + __slots__ = ( + "_configure_started", + "_configure_finished", + "_attribute_options", + "_has_dataclass_arguments", + "parent", + "key", + "info", + "doc", + ) + + _cache_key_traversal: _TraverseInternalsType = [ + ("parent", visitors.ExtendedInternalTraversal.dp_has_cache_key), + ("key", visitors.ExtendedInternalTraversal.dp_string), + ] + + if not TYPE_CHECKING: + cascade = None + + is_property = True + """Part of the InspectionAttr interface; states this object is a + mapper property. + + """ + + comparator: PropComparator[_T] + """The :class:`_orm.PropComparator` instance that implements SQL + expression construction on behalf of this mapped attribute.""" + + key: str + """name of class attribute""" + + parent: Mapper[Any] + """the :class:`.Mapper` managing this property.""" + + _is_relationship = False + + _links_to_entity: bool + """True if this MapperProperty refers to a mapped entity. + + Should only be True for Relationship, False for all others. + + """ + + doc: Optional[str] + """optional documentation string""" + + info: _InfoType + """Info dictionary associated with the object, allowing user-defined + data to be associated with this :class:`.InspectionAttr`. + + The dictionary is generated when first accessed. Alternatively, + it can be specified as a constructor argument to the + :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite` + functions. + + .. seealso:: + + :attr:`.QueryableAttribute.info` + + :attr:`.SchemaItem.info` + + """ + + def _memoized_attr_info(self) -> _InfoType: + """Info dictionary associated with the object, allowing user-defined + data to be associated with this :class:`.InspectionAttr`. + + The dictionary is generated when first accessed. Alternatively, + it can be specified as a constructor argument to the + :func:`.column_property`, :func:`_orm.relationship`, or + :func:`.composite` + functions. + + .. seealso:: + + :attr:`.QueryableAttribute.info` + + :attr:`.SchemaItem.info` + + """ + return {} + + def setup( + self, + context: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + adapter: Optional[ORMAdapter], + **kwargs: Any, + ) -> None: + """Called by Query for the purposes of constructing a SQL statement. + + Each MapperProperty associated with the target mapper processes the + statement referenced by the query context, adding columns and/or + criterion as appropriate. + + """ + + def create_row_processor( + self, + context: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + mapper: Mapper[Any], + result: Result[Any], + adapter: Optional[ORMAdapter], + populators: _PopulatorDict, + ) -> None: + """Produce row processing functions and append to the given + set of populators lists. + + """ + + def cascade_iterator( + self, + type_: str, + state: InstanceState[Any], + dict_: _InstanceDict, + visited_states: Set[InstanceState[Any]], + halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None, + ) -> Iterator[ + Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict] + ]: + """Iterate through instances related to the given instance for + a particular 'cascade', starting with this MapperProperty. + + Return an iterator3-tuples (instance, mapper, state). + + Note that the 'cascade' collection on this MapperProperty is + checked first for the given type before cascade_iterator is called. + + This method typically only applies to Relationship. + + """ + + return iter(()) + + def set_parent(self, parent: Mapper[Any], init: bool) -> None: + """Set the parent mapper that references this MapperProperty. + + This method is overridden by some subclasses to perform extra + setup when the mapper is first known. + + """ + self.parent = parent + + def instrument_class(self, mapper: Mapper[Any]) -> None: + """Hook called by the Mapper to the property to initiate + instrumentation of the class attribute managed by this + MapperProperty. + + The MapperProperty here will typically call out to the + attributes module to set up an InstrumentedAttribute. + + This step is the first of two steps to set up an InstrumentedAttribute, + and is called early in the mapper setup process. + + The second step is typically the init_class_attribute step, + called from StrategizedProperty via the post_instrument_class() + hook. This step assigns additional state to the InstrumentedAttribute + (specifically the "impl") which has been determined after the + MapperProperty has determined what kind of persistence + management it needs to do (e.g. scalar, object, collection, etc). + + """ + + def __init__( + self, + attribute_options: Optional[_AttributeOptions] = None, + _assume_readonly_dc_attributes: bool = False, + ) -> None: + self._configure_started = False + self._configure_finished = False + + if _assume_readonly_dc_attributes: + default_attrs = _DEFAULT_READONLY_ATTRIBUTE_OPTIONS + else: + default_attrs = _DEFAULT_ATTRIBUTE_OPTIONS + + if attribute_options and attribute_options != default_attrs: + self._has_dataclass_arguments = True + self._attribute_options = attribute_options + else: + self._has_dataclass_arguments = False + self._attribute_options = default_attrs + + def init(self) -> None: + """Called after all mappers are created to assemble + relationships between mappers and perform other post-mapper-creation + initialization steps. + + + """ + self._configure_started = True + self.do_init() + self._configure_finished = True + + @property + def class_attribute(self) -> InstrumentedAttribute[_T]: + """Return the class-bound descriptor corresponding to this + :class:`.MapperProperty`. + + This is basically a ``getattr()`` call:: + + return getattr(self.parent.class_, self.key) + + I.e. if this :class:`.MapperProperty` were named ``addresses``, + and the class to which it is mapped is ``User``, this sequence + is possible:: + + >>> from sqlalchemy import inspect + >>> mapper = inspect(User) + >>> addresses_property = mapper.attrs.addresses + >>> addresses_property.class_attribute is User.addresses + True + >>> User.addresses.property is addresses_property + True + + + """ + + return getattr(self.parent.class_, self.key) # type: ignore + + def do_init(self) -> None: + """Perform subclass-specific initialization post-mapper-creation + steps. + + This is a template method called by the ``MapperProperty`` + object's init() method. + + """ + + def post_instrument_class(self, mapper: Mapper[Any]) -> None: + """Perform instrumentation adjustments that need to occur + after init() has completed. + + The given Mapper is the Mapper invoking the operation, which + may not be the same Mapper as self.parent in an inheritance + scenario; however, Mapper will always at least be a sub-mapper of + self.parent. + + This method is typically used by StrategizedProperty, which delegates + it to LoaderStrategy.init_class_attribute() to perform final setup + on the class-bound InstrumentedAttribute. + + """ + + def merge( + self, + session: Session, + source_state: InstanceState[Any], + source_dict: _InstanceDict, + dest_state: InstanceState[Any], + dest_dict: _InstanceDict, + load: bool, + _recursive: Dict[Any, object], + _resolve_conflict_map: Dict[_IdentityKeyType[Any], object], + ) -> None: + """Merge the attribute represented by this ``MapperProperty`` + from source to destination object. + + """ + + def __repr__(self) -> str: + return "<%s at 0x%x; %s>" % ( + self.__class__.__name__, + id(self), + getattr(self, "key", "no key"), + ) + + +@inspection._self_inspects +class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators): + r"""Defines SQL operations for ORM mapped attributes. + + SQLAlchemy allows for operators to + be redefined at both the Core and ORM level. :class:`.PropComparator` + is the base class of operator redefinition for ORM-level operations, + including those of :class:`.ColumnProperty`, + :class:`.Relationship`, and :class:`.Composite`. + + User-defined subclasses of :class:`.PropComparator` may be created. The + built-in Python comparison and math operator methods, such as + :meth:`.operators.ColumnOperators.__eq__`, + :meth:`.operators.ColumnOperators.__lt__`, and + :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide + new operator behavior. The custom :class:`.PropComparator` is passed to + the :class:`.MapperProperty` instance via the ``comparator_factory`` + argument. In each case, + the appropriate subclass of :class:`.PropComparator` should be used:: + + # definition of custom PropComparator subclasses + + from sqlalchemy.orm.properties import ( + ColumnProperty, + Composite, + Relationship, + ) + + + class MyColumnComparator(ColumnProperty.Comparator): + def __eq__(self, other): + return self.__clause_element__() == other + + + class MyRelationshipComparator(Relationship.Comparator): + def any(self, expression): + "define the 'any' operation" + # ... + + + class MyCompositeComparator(Composite.Comparator): + def __gt__(self, other): + "redefine the 'greater than' operation" + + return sql.and_( + *[ + a > b + for a, b in zip( + self.__clause_element__().clauses, + other.__composite_values__(), + ) + ] + ) + + + # application of custom PropComparator subclasses + + from sqlalchemy.orm import column_property, relationship, composite + from sqlalchemy import Column, String + + + class SomeMappedClass(Base): + some_column = column_property( + Column("some_column", String), + comparator_factory=MyColumnComparator, + ) + + some_relationship = relationship( + SomeOtherClass, comparator_factory=MyRelationshipComparator + ) + + some_composite = composite( + Column("a", String), + Column("b", String), + comparator_factory=MyCompositeComparator, + ) + + Note that for column-level operator redefinition, it's usually + simpler to define the operators at the Core level, using the + :attr:`.TypeEngine.comparator_factory` attribute. See + :ref:`types_operators` for more detail. + + .. seealso:: + + :class:`.ColumnProperty.Comparator` + + :class:`.Relationship.Comparator` + + :class:`.Composite.Comparator` + + :class:`.ColumnOperators` + + :ref:`types_operators` + + :attr:`.TypeEngine.comparator_factory` + + """ + + __slots__ = "prop", "_parententity", "_adapt_to_entity" + + __visit_name__ = "orm_prop_comparator" + + _parententity: _InternalEntityType[Any] + _adapt_to_entity: Optional[AliasedInsp[Any]] + prop: RODescriptorReference[MapperProperty[_T_co]] + + def __init__( + self, + prop: MapperProperty[_T], + parentmapper: _InternalEntityType[Any], + adapt_to_entity: Optional[AliasedInsp[Any]] = None, + ): + self.prop = prop + self._parententity = adapt_to_entity or parentmapper + self._adapt_to_entity = adapt_to_entity + + @util.non_memoized_property + def property(self) -> MapperProperty[_T_co]: + """Return the :class:`.MapperProperty` associated with this + :class:`.PropComparator`. + + + Return values here will commonly be instances of + :class:`.ColumnProperty` or :class:`.Relationship`. + + + """ + return self.prop + + def __clause_element__(self) -> roles.ColumnsClauseRole: + raise NotImplementedError("%r" % self) + + def _bulk_update_tuples( + self, value: Any + ) -> Sequence[Tuple[_DMLColumnArgument, Any]]: + """Receive a SQL expression that represents a value in the SET + clause of an UPDATE statement. + + Return a tuple that can be passed to a :class:`_expression.Update` + construct. + + """ + + return [(cast("_DMLColumnArgument", self.__clause_element__()), value)] + + def adapt_to_entity( + self, adapt_to_entity: AliasedInsp[Any] + ) -> PropComparator[_T_co]: + """Return a copy of this PropComparator which will use the given + :class:`.AliasedInsp` to produce corresponding expressions. + """ + return self.__class__(self.prop, self._parententity, adapt_to_entity) + + @util.ro_non_memoized_property + def _parentmapper(self) -> Mapper[Any]: + """legacy; this is renamed to _parententity to be + compatible with QueryableAttribute.""" + return self._parententity.mapper + + def _criterion_exists( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[Any]: + return self.prop.comparator._criterion_exists(criterion, **kwargs) + + @util.ro_non_memoized_property + def adapter(self) -> Optional[_ORMAdapterProto]: + """Produce a callable that adapts column expressions + to suit an aliased version of this comparator. + + """ + if self._adapt_to_entity is None: + return None + else: + return self._adapt_to_entity._orm_adapt_element + + @util.ro_non_memoized_property + def info(self) -> _InfoType: + return self.prop.info + + @staticmethod + def _any_op(a: Any, b: Any, **kwargs: Any) -> Any: + return a.any(b, **kwargs) + + @staticmethod + def _has_op(left: Any, other: Any, **kwargs: Any) -> Any: + return left.has(other, **kwargs) + + @staticmethod + def _of_type_op(a: Any, class_: Any) -> Any: + return a.of_type(class_) + + any_op = cast(operators.OperatorType, _any_op) + has_op = cast(operators.OperatorType, _has_op) + of_type_op = cast(operators.OperatorType, _of_type_op) + + if typing.TYPE_CHECKING: + + def operate( + self, op: OperatorType, *other: Any, **kwargs: Any + ) -> ColumnElement[Any]: ... + + def reverse_operate( + self, op: OperatorType, other: Any, **kwargs: Any + ) -> ColumnElement[Any]: ... + + def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]: + r"""Redefine this object in terms of a polymorphic subclass, + :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased` + construct. + + Returns a new PropComparator from which further criterion can be + evaluated. + + e.g.:: + + query.join(Company.employees.of_type(Engineer)).filter( + Engineer.name == "foo" + ) + + :param \class_: a class or mapper indicating that criterion will be + against this specific subclass. + + .. seealso:: + + :ref:`orm_queryguide_joining_relationships_aliased` - in the + :ref:`queryguide_toplevel` + + :ref:`inheritance_of_type` + + """ + + return self.operate(PropComparator.of_type_op, class_) # type: ignore + + def and_( + self, *criteria: _ColumnExpressionArgument[bool] + ) -> PropComparator[bool]: + """Add additional criteria to the ON clause that's represented by this + relationship attribute. + + E.g.:: + + + stmt = select(User).join( + User.addresses.and_(Address.email_address != "foo") + ) + + stmt = select(User).options( + joinedload(User.addresses.and_(Address.email_address != "foo")) + ) + + .. versionadded:: 1.4 + + .. seealso:: + + :ref:`orm_queryguide_join_on_augmented` + + :ref:`loader_option_criteria` + + :func:`.with_loader_criteria` + + """ + return self.operate(operators.and_, *criteria) # type: ignore + + def any( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: + r"""Return a SQL expression representing true if this element + references a member which meets the given criterion. + + The usual implementation of ``any()`` is + :meth:`.Relationship.Comparator.any`. + + :param criterion: an optional ClauseElement formulated against the + member class' table or attributes. + + :param \**kwargs: key/value pairs corresponding to member class + attribute names which will be compared via equality to the + corresponding values. + + """ + + return self.operate(PropComparator.any_op, criterion, **kwargs) + + def has( + self, + criterion: Optional[_ColumnExpressionArgument[bool]] = None, + **kwargs: Any, + ) -> ColumnElement[bool]: + r"""Return a SQL expression representing true if this element + references a member which meets the given criterion. + + The usual implementation of ``has()`` is + :meth:`.Relationship.Comparator.has`. + + :param criterion: an optional ClauseElement formulated against the + member class' table or attributes. + + :param \**kwargs: key/value pairs corresponding to member class + attribute names which will be compared via equality to the + corresponding values. + + """ + + return self.operate(PropComparator.has_op, criterion, **kwargs) + + +class StrategizedProperty(MapperProperty[_T]): + """A MapperProperty which uses selectable strategies to affect + loading behavior. + + There is a single strategy selected by default. Alternate + strategies can be selected at Query time through the usage of + ``StrategizedOption`` objects via the Query.options() method. + + The mechanics of StrategizedProperty are used for every Query + invocation for every mapped attribute participating in that Query, + to determine first how the attribute will be rendered in SQL + and secondly how the attribute will retrieve a value from a result + row and apply it to a mapped object. The routines here are very + performance-critical. + + """ + + __slots__ = ( + "_strategies", + "strategy", + "_wildcard_token", + "_default_path_loader_key", + "strategy_key", + ) + inherit_cache = True + strategy_wildcard_key: ClassVar[str] + + strategy_key: _StrategyKey + + _strategies: Dict[_StrategyKey, LoaderStrategy] + + def _memoized_attr__wildcard_token(self) -> Tuple[str]: + return ( + f"{self.strategy_wildcard_key}:{path_registry._WILDCARD_TOKEN}", + ) + + def _memoized_attr__default_path_loader_key( + self, + ) -> Tuple[str, Tuple[str]]: + return ( + "loader", + (f"{self.strategy_wildcard_key}:{path_registry._DEFAULT_TOKEN}",), + ) + + def _get_context_loader( + self, context: ORMCompileState, path: AbstractEntityRegistry + ) -> Optional[_LoadElement]: + load: Optional[_LoadElement] = None + + search_path = path[self] + + # search among: exact match, "attr.*", "default" strategy + # if any. + for path_key in ( + search_path._loader_key, + search_path._wildcard_path_loader_key, + search_path._default_path_loader_key, + ): + if path_key in context.attributes: + load = context.attributes[path_key] + break + + # note that if strategy_options.Load is placing non-actionable + # objects in the context like defaultload(), we would + # need to continue the loop here if we got such an + # option as below. + # if load.strategy or load.local_opts: + # break + + return load + + def _get_strategy(self, key: _StrategyKey) -> LoaderStrategy: + try: + return self._strategies[key] + except KeyError: + pass + + # run outside to prevent transfer of exception context + cls = self._strategy_lookup(self, *key) + # this previously was setting self._strategies[cls], that's + # a bad idea; should use strategy key at all times because every + # strategy has multiple keys at this point + self._strategies[key] = strategy = cls(self, key) + return strategy + + def setup( + self, + context: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + adapter: Optional[ORMAdapter], + **kwargs: Any, + ) -> None: + loader = self._get_context_loader(context, path) + if loader and loader.strategy: + strat = self._get_strategy(loader.strategy) + else: + strat = self.strategy + strat.setup_query( + context, query_entity, path, loader, adapter, **kwargs + ) + + def create_row_processor( + self, + context: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + mapper: Mapper[Any], + result: Result[Any], + adapter: Optional[ORMAdapter], + populators: _PopulatorDict, + ) -> None: + loader = self._get_context_loader(context, path) + if loader and loader.strategy: + strat = self._get_strategy(loader.strategy) + else: + strat = self.strategy + strat.create_row_processor( + context, + query_entity, + path, + loader, + mapper, + result, + adapter, + populators, + ) + + def do_init(self) -> None: + self._strategies = {} + self.strategy = self._get_strategy(self.strategy_key) + + def post_instrument_class(self, mapper: Mapper[Any]) -> None: + if ( + not self.parent.non_primary + and not mapper.class_manager._attr_has_impl(self.key) + ): + self.strategy.init_class_attribute(mapper) + + _all_strategies: collections.defaultdict[ + Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]] + ] = collections.defaultdict(dict) + + @classmethod + def strategy_for(cls, **kw: Any) -> Callable[[_TLS], _TLS]: + def decorate(dec_cls: _TLS) -> _TLS: + # ensure each subclass of the strategy has its + # own _strategy_keys collection + if "_strategy_keys" not in dec_cls.__dict__: + dec_cls._strategy_keys = [] + key = tuple(sorted(kw.items())) + cls._all_strategies[cls][key] = dec_cls + dec_cls._strategy_keys.append(key) + return dec_cls + + return decorate + + @classmethod + def _strategy_lookup( + cls, requesting_property: MapperProperty[Any], *key: Any + ) -> Type[LoaderStrategy]: + requesting_property.parent._with_polymorphic_mappers + + for prop_cls in cls.__mro__: + if prop_cls in cls._all_strategies: + if TYPE_CHECKING: + assert issubclass(prop_cls, MapperProperty) + strategies = cls._all_strategies[prop_cls] + try: + return strategies[key] + except KeyError: + pass + + for property_type, strats in cls._all_strategies.items(): + if key in strats: + intended_property_type = property_type + actual_strategy = strats[key] + break + else: + intended_property_type = None + actual_strategy = None + + raise orm_exc.LoaderStrategyException( + cls, + requesting_property, + intended_property_type, + actual_strategy, + key, + ) + + +class ORMOption(ExecutableOption): + """Base class for option objects that are passed to ORM queries. + + These options may be consumed by :meth:`.Query.options`, + :meth:`.Select.options`, or in a more general sense by any + :meth:`.Executable.options` method. They are interpreted at + statement compile time or execution time in modern use. The + deprecated :class:`.MapperOption` is consumed at ORM query construction + time. + + .. versionadded:: 1.4 + + """ + + __slots__ = () + + _is_legacy_option = False + + propagate_to_loaders = False + """if True, indicate this option should be carried along + to "secondary" SELECT statements that occur for relationship + lazy loaders as well as attribute load / refresh operations. + + """ + + _is_core = False + + _is_user_defined = False + + _is_compile_state = False + + _is_criteria_option = False + + _is_strategy_option = False + + def _adapt_cached_option_to_uncached_option( + self, context: QueryContext, uncached_opt: ORMOption + ) -> ORMOption: + """adapt this option to the "uncached" version of itself in a + loader strategy context. + + given "self" which is an option from a cached query, as well as the + corresponding option from the uncached version of the same query, + return the option we should use in a new query, in the context of a + loader strategy being asked to load related rows on behalf of that + cached query, which is assumed to be building a new query based on + entities passed to us from the cached query. + + Currently this routine chooses between "self" and "uncached" without + manufacturing anything new. If the option is itself a loader strategy + option which has a path, that path needs to match to the entities being + passed to us by the cached query, so the :class:`_orm.Load` subclass + overrides this to return "self". For all other options, we return the + uncached form which may have changing state, such as a + with_loader_criteria() option which will very often have new state. + + This routine could in the future involve + generating a new option based on both inputs if use cases arise, + such as if with_loader_criteria() needed to match up to + ``AliasedClass`` instances given in the parent query. + + However, longer term it might be better to restructure things such that + ``AliasedClass`` entities are always matched up on their cache key, + instead of identity, in things like paths and such, so that this whole + issue of "the uncached option does not match the entities" goes away. + However this would make ``PathRegistry`` more complicated and difficult + to debug as well as potentially less performant in that it would be + hashing enormous cache keys rather than a simple AliasedInsp. UNLESS, + we could get cache keys overall to be reliably hashed into something + like an md5 key. + + .. versionadded:: 1.4.41 + + """ + if uncached_opt is not None: + return uncached_opt + else: + return self + + +class CompileStateOption(HasCacheKey, ORMOption): + """base for :class:`.ORMOption` classes that affect the compilation of + a SQL query and therefore need to be part of the cache key. + + .. note:: :class:`.CompileStateOption` is generally non-public and + should not be used as a base class for user-defined options; instead, + use :class:`.UserDefinedOption`, which is easier to use as it does not + interact with ORM compilation internals or caching. + + :class:`.CompileStateOption` defines an internal attribute + ``_is_compile_state=True`` which has the effect of the ORM compilation + routines for SELECT and other statements will call upon these options when + a SQL string is being compiled. As such, these classes implement + :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal`` + structures. + + The :class:`.CompileStateOption` class is used to implement the ORM + :class:`.LoaderOption` and :class:`.CriteriaOption` classes. + + .. versionadded:: 1.4.28 + + + """ + + __slots__ = () + + _is_compile_state = True + + def process_compile_state(self, compile_state: ORMCompileState) -> None: + """Apply a modification to a given :class:`.ORMCompileState`. + + This method is part of the implementation of a particular + :class:`.CompileStateOption` and is only invoked internally + when an ORM query is compiled. + + """ + + def process_compile_state_replaced_entities( + self, + compile_state: ORMCompileState, + mapper_entities: Sequence[_MapperEntity], + ) -> None: + """Apply a modification to a given :class:`.ORMCompileState`, + given entities that were replaced by with_only_columns() or + with_entities(). + + This method is part of the implementation of a particular + :class:`.CompileStateOption` and is only invoked internally + when an ORM query is compiled. + + .. versionadded:: 1.4.19 + + """ + + +class LoaderOption(CompileStateOption): + """Describe a loader modification to an ORM statement at compilation time. + + .. versionadded:: 1.4 + + """ + + __slots__ = () + + def process_compile_state_replaced_entities( + self, + compile_state: ORMCompileState, + mapper_entities: Sequence[_MapperEntity], + ) -> None: + self.process_compile_state(compile_state) + + +class CriteriaOption(CompileStateOption): + """Describe a WHERE criteria modification to an ORM statement at + compilation time. + + .. versionadded:: 1.4 + + """ + + __slots__ = () + + _is_criteria_option = True + + def get_global_criteria(self, attributes: Dict[str, Any]) -> None: + """update additional entity criteria options in the given + attributes dictionary. + + """ + + +class UserDefinedOption(ORMOption): + """Base class for a user-defined option that can be consumed from the + :meth:`.SessionEvents.do_orm_execute` event hook. + + """ + + __slots__ = ("payload",) + + _is_legacy_option = False + + _is_user_defined = True + + propagate_to_loaders = False + """if True, indicate this option should be carried along + to "secondary" Query objects produced during lazy loads + or refresh operations. + + """ + + def __init__(self, payload: Optional[Any] = None): + self.payload = payload + + +@util.deprecated_cls( + "1.4", + "The :class:`.MapperOption class is deprecated and will be removed " + "in a future release. For " + "modifications to queries on a per-execution basis, use the " + ":class:`.UserDefinedOption` class to establish state within a " + ":class:`.Query` or other Core statement, then use the " + ":meth:`.SessionEvents.before_orm_execute` hook to consume them.", + constructor=None, +) +class MapperOption(ORMOption): + """Describe a modification to a Query""" + + __slots__ = () + + _is_legacy_option = True + + propagate_to_loaders = False + """if True, indicate this option should be carried along + to "secondary" Query objects produced during lazy loads + or refresh operations. + + """ + + def process_query(self, query: Query[Any]) -> None: + """Apply a modification to the given :class:`_query.Query`.""" + + def process_query_conditionally(self, query: Query[Any]) -> None: + """same as process_query(), except that this option may not + apply to the given query. + + This is typically applied during a lazy load or scalar refresh + operation to propagate options stated in the original Query to the + new Query being used for the load. It occurs for those options that + specify propagate_to_loaders=True. + + """ + + self.process_query(query) + + +class LoaderStrategy: + """Describe the loading behavior of a StrategizedProperty object. + + The ``LoaderStrategy`` interacts with the querying process in three + ways: + + * it controls the configuration of the ``InstrumentedAttribute`` + placed on a class to handle the behavior of the attribute. this + may involve setting up class-level callable functions to fire + off a select operation when the attribute is first accessed + (i.e. a lazy load) + + * it processes the ``QueryContext`` at statement construction time, + where it can modify the SQL statement that is being produced. + For example, simple column attributes will add their represented + column to the list of selected columns, a joined eager loader + may establish join clauses to add to the statement. + + * It produces "row processor" functions at result fetching time. + These "row processor" functions populate a particular attribute + on a particular mapped instance. + + """ + + __slots__ = ( + "parent_property", + "is_class_level", + "parent", + "key", + "strategy_key", + "strategy_opts", + ) + + _strategy_keys: ClassVar[List[_StrategyKey]] + + def __init__( + self, parent: MapperProperty[Any], strategy_key: _StrategyKey + ): + self.parent_property = parent + self.is_class_level = False + self.parent = self.parent_property.parent + self.key = self.parent_property.key + self.strategy_key = strategy_key + self.strategy_opts = dict(strategy_key) + + def init_class_attribute(self, mapper: Mapper[Any]) -> None: + pass + + def setup_query( + self, + compile_state: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + loadopt: Optional[_LoadElement], + adapter: Optional[ORMAdapter], + **kwargs: Any, + ) -> None: + """Establish column and other state for a given QueryContext. + + This method fulfills the contract specified by MapperProperty.setup(). + + StrategizedProperty delegates its setup() method + directly to this method. + + """ + + def create_row_processor( + self, + context: ORMCompileState, + query_entity: _MapperEntity, + path: AbstractEntityRegistry, + loadopt: Optional[_LoadElement], + mapper: Mapper[Any], + result: Result[Any], + adapter: Optional[ORMAdapter], + populators: _PopulatorDict, + ) -> None: + """Establish row processing functions for a given QueryContext. + + This method fulfills the contract specified by + MapperProperty.create_row_processor(). + + StrategizedProperty delegates its create_row_processor() method + directly to this method. + + """ + + def __str__(self) -> str: + return str(self.parent_property) diff --git a/python/user_packages/Python313/site-packages/sqlalchemy/orm/loading.py b/python/user_packages/Python313/site-packages/sqlalchemy/orm/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e180b47689b74e6be3ee326bca1bccb12bdf02 --- /dev/null +++ b/python/user_packages/Python313/site-packages/sqlalchemy/orm/loading.py @@ -0,0 +1,1686 @@ +# orm/loading.py +# Copyright (C) 2005-2026 the SQLAlchemy authors and contributors +# +# +# This module is part of SQLAlchemy and is released under +# the MIT License: https://www.opensource.org/licenses/mit-license.php +# mypy: ignore-errors + + +"""private module containing functions used to convert database +rows into object instances and associated state. + +the functions here are called primarily by Query, Mapper, +as well as some of the attribute loading strategies. + +""" + +from __future__ import annotations + +from typing import Any +from typing import Dict +from typing import Iterable +from typing import List +from typing import Mapping +from typing import Optional +from typing import Sequence +from typing import Tuple +from typing import TYPE_CHECKING +from typing import TypeVar +from typing import Union + +from . import attributes +from . import exc as orm_exc +from . import path_registry +from .base import _DEFER_FOR_STATE +from .base import _RAISE_FOR_STATE +from .base import _SET_DEFERRED_EXPIRED +from .base import PassiveFlag +from .context import FromStatement +from .context import ORMCompileState +from .context import QueryContext +from .strategies import SelectInLoader +from .util import _none_set +from .util import state_str +from .. import exc as sa_exc +from .. import util +from ..engine import result_tuple +from ..engine.result import ChunkedIteratorResult +from ..engine.result import FrozenResult +from ..engine.result import SimpleResultMetaData +from ..sql import select +from ..sql import util as sql_util +from ..sql.selectable import ForUpdateArg +from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL +from ..sql.selectable import SelectState +from ..util import EMPTY_DICT + +if TYPE_CHECKING: + from ._typing import _IdentityKeyType + from .base import LoaderCallableStatus + from .interfaces import ORMOption + from .mapper import Mapper + from .query import Query + from .session import Session + from .state import InstanceState + from ..engine.cursor import CursorResult + from ..engine.interfaces import _ExecuteOptions + from ..engine.result import Result + from ..sql import Select + +_T = TypeVar("_T", bound=Any) +_O = TypeVar("_O", bound=object) +_new_runid = util.counter() + + +_PopulatorDict = Dict[str, List[Tuple[str, Any]]] + + +def instances(cursor: CursorResult[Any], context: QueryContext) -> Result[Any]: + """Return a :class:`.Result` given an ORM query context. + + :param cursor: a :class:`.CursorResult`, generated by a statement + which came from :class:`.ORMCompileState` + + :param context: a :class:`.QueryContext` object + + :return: a :class:`.Result` object representing ORM results + + .. versionchanged:: 1.4 The instances() function now uses + :class:`.Result` objects and has an all new interface. + + """ + + context.runid = _new_runid() + + if context.top_level_context: + is_top_level = False + context.post_load_paths = context.top_level_context.post_load_paths + else: + is_top_level = True + context.post_load_paths = {} + + compile_state = context.compile_state + filtered = compile_state._has_mapper_entities + single_entity = ( + not context.load_options._only_return_tuples + and len(compile_state._entities) == 1 + and compile_state._entities[0].supports_single_entity + ) + + try: + (process, labels, extra) = list( + zip( + *[ + query_entity.row_processor(context, cursor) + for query_entity in context.compile_state._entities + ] + ) + ) + + if context.yield_per and ( + context.loaders_require_buffering + or context.loaders_require_uniquing + ): + raise sa_exc.InvalidRequestError( + "Can't use yield_per with eager loaders that require uniquing " + "or row buffering, e.g. joinedload() against collections " + "or subqueryload(). Consider the selectinload() strategy " + "for better flexibility in loading objects." + ) + + except Exception: + with util.safe_reraise(): + cursor.close() + + def _no_unique(entry): + raise sa_exc.InvalidRequestError( + "Can't use the ORM yield_per feature in conjunction with unique()" + ) + + def _not_hashable(datatype, *, legacy=False, uncertain=False): + if not legacy: + + def go(obj): + if uncertain: + try: + return hash(obj) + except: + pass + + raise sa_exc.InvalidRequestError( + "Can't apply uniqueness to row tuple containing value of " + f"""type {datatype!r}; { + 'the values returned appear to be' + if uncertain + else 'this datatype produces' + } non-hashable values""" + ) + + return go + elif not uncertain: + return id + else: + _use_id = False + + def go(obj): + nonlocal _use_id + + if not _use_id: + try: + return hash(obj) + except: + pass + + # in #10459, we considered using a warning here, however + # as legacy query uses result.unique() in all cases, this + # would lead to too many warning cases. + _use_id = True + + return id(obj) + + return go + + unique_filters = [ + ( + _no_unique + if context.yield_per + else ( + _not_hashable( + ent.column.type, # type: ignore + legacy=context.load_options._legacy_uniquing, + uncertain=ent._null_column_type, + ) + if ( + not ent.use_id_for_hash + and (ent._non_hashable_value or ent._null_column_type) + ) + else id if ent.use_id_for_hash else None + ) + ) + for ent in context.compile_state._entities + ] + + row_metadata = SimpleResultMetaData( + labels, extra, _unique_filters=unique_filters + ) + + def chunks(size): # type: ignore + while True: + yield_per = size + + context.partials = {} + + if yield_per: + fetch = cursor.fetchmany(yield_per) + + if not fetch: + break + else: + fetch = cursor._raw_all_rows() + + if single_entity: + proc = process[0] + rows = [proc(row) for row in fetch] + else: + rows = [ + tuple([proc(row) for proc in process]) for row in fetch + ] + + # if we are the originating load from a query, meaning we + # aren't being called as a result of a nested "post load", + # iterate through all the collected post loaders and fire them + # off. Previously this used to work recursively, however that + # prevented deeply nested structures from being loadable + if is_top_level: + if yield_per: + # if using yield per, memoize the state of the + # collection so that it can be restored + top_level_post_loads = list( + context.post_load_paths.items() + ) + + while context.post_load_paths: + post_loads = list(context.post_load_paths.items()) + context.post_load_paths.clear() + for path, post_load in post_loads: + post_load.invoke(context, path) + + if yield_per: + context.post_load_paths.clear() + context.post_load_paths.update(top_level_post_loads) + + yield rows + + if not yield_per: + break + + if context.execution_options.get("prebuffer_rows", False): + # this is a bit of a hack at the moment. + # I would rather have some option in the result to pre-buffer + # internally. + _prebuffered = list(chunks(None)) + + def chunks(size): + return iter(_prebuffered) + + result = ChunkedIteratorResult( + row_metadata, + chunks, + source_supports_scalars=single_entity, + raw=cursor, + dynamic_yield_per=cursor.context._is_server_side, + ) + + # filtered and single_entity are used to indicate to legacy Query that the + # query has ORM entities, so legacy deduping and scalars should be called + # on the result. + result._attributes = result._attributes.union( + dict(filtered=filtered, is_single_entity=single_entity) + ) + + # multi_row_eager_loaders OTOH is specific to joinedload. + if context.compile_state.multi_row_eager_loaders: + + def require_unique(obj): + raise sa_exc.InvalidRequestError( + "The unique() method must be invoked on this Result, " + "as it contains results that include joined eager loads " + "against collections" + ) + + result._unique_filter_state = (None, require_unique) + + if context.yield_per: + result.yield_per(context.yield_per) + + return result + + +@util.preload_module("sqlalchemy.orm.context") +def merge_frozen_result(session, statement, frozen_result, load=True): + """Merge a :class:`_engine.FrozenResult` back into a :class:`_orm.Session`, + returning a new :class:`_engine.Result` object with :term:`persistent` + objects. + + See the section :ref:`do_orm_execute_re_executing` for an example. + + .. seealso:: + + :ref:`do_orm_execute_re_executing` + + :meth:`_engine.Result.freeze` + + :class:`_engine.FrozenResult` + + """ + querycontext = util.preloaded.orm_context + + if load: + # flush current contents if we expect to load data + session._autoflush() + + ctx = querycontext.ORMSelectCompileState._create_entities_collection( + statement, legacy=False + ) + + autoflush = session.autoflush + try: + session.autoflush = False + mapped_entities = [ + i + for i, e in enumerate(ctx._entities) + if isinstance(e, querycontext._MapperEntity) + ] + keys = [ent._label_name for ent in ctx._entities] + + keyed_tuple = result_tuple( + keys, [ent._extra_entities for ent in ctx._entities] + ) + + result = [] + for newrow in frozen_result.rewrite_rows(): + for i in mapped_entities: + if newrow[i] is not None: + newrow[i] = session._merge( + attributes.instance_state(newrow[i]), + attributes.instance_dict(newrow[i]), + load=load, + _recursive={}, + _resolve_conflict_map={}, + ) + + result.append(keyed_tuple(newrow)) + + return frozen_result.with_new_rows(result) + finally: + session.autoflush = autoflush + + +@util.became_legacy_20( + ":func:`_orm.merge_result`", + alternative="The function as well as the method on :class:`_orm.Query` " + "is superseded by the :func:`_orm.merge_frozen_result` function.", +) +@util.preload_module("sqlalchemy.orm.context") +def merge_result( + query: Query[Any], + iterator: Union[FrozenResult, Iterable[Sequence[Any]], Iterable[object]], + load: bool = True, +) -> Union[FrozenResult, Iterable[Any]]: + """Merge a result into the given :class:`.Query` object's Session. + + See :meth:`_orm.Query.merge_result` for top-level documentation on this + function. + + """ + + querycontext = util.preloaded.orm_context + + session = query.session + if load: + # flush current contents if we expect to load data + session._autoflush() + + # TODO: need test coverage and documentation for the FrozenResult + # use case. + if isinstance(iterator, FrozenResult): + frozen_result = iterator + iterator = iter(frozen_result.data) + else: + frozen_result = None + + ctx = querycontext.ORMSelectCompileState._create_entities_collection( + query, legacy=True + ) + + autoflush = session.autoflush + try: + session.autoflush = False + single_entity = not frozen_result and len(ctx._entities) == 1 + + if single_entity: + if isinstance(ctx._entities[0], querycontext._MapperEntity): + result = [ + session._merge( + attributes.instance_state(instance), + attributes.instance_dict(instance), + load=load, + _recursive={}, + _resolve_conflict_map={}, + ) + for instance in iterator + ] + else: + result = list(iterator) + else: + mapped_entities = [ + i + for i, e in enumerate(ctx._entities) + if isinstance(e, querycontext._MapperEntity) + ] + result = [] + keys = [ent._label_name for ent in ctx._entities] + + keyed_tuple = result_tuple( + keys, [ent._extra_entities for ent in ctx._entities] + ) + + for row in iterator: + newrow = list(row) + for i in mapped_entities: + if newrow[i] is not None: + newrow[i] = session._merge( + attributes.instance_state(newrow[i]), + attributes.instance_dict(newrow[i]), + load=load, + _recursive={}, + _resolve_conflict_map={}, + ) + result.append(keyed_tuple(newrow)) + + if frozen_result: + return frozen_result.with_new_rows(result) + else: + return iter(result) + finally: + session.autoflush = autoflush + + +def get_from_identity( + session: Session, + mapper: Mapper[_O], + key: _IdentityKeyType[_O], + passive: PassiveFlag, +) -> Union[LoaderCallableStatus, Optional[_O]]: + """Look up the given key in the given session's identity map, + check the object for expired state if found. + + """ + instance = session.identity_map.get(key) + if instance is not None: + state = attributes.instance_state(instance) + + if mapper.inherits and not state.mapper.isa(mapper): + return attributes.PASSIVE_CLASS_MISMATCH + + # expired - ensure it still exists + if state.expired: + if not passive & attributes.SQL_OK: + # TODO: no coverage here + return attributes.PASSIVE_NO_RESULT + elif not passive & attributes.RELATED_OBJECT_OK: + # this mode is used within a flush and the instance's + # expired state will be checked soon enough, if necessary. + # also used by immediateloader for a mutually-dependent + # o2m->m2m load, :ticket:`6301` + return instance + try: + state._load_expired(state, passive) + except orm_exc.ObjectDeletedError: + session._remove_newly_deleted([state]) + return None + return instance + else: + return None + + +def load_on_ident( + session: Session, + statement: Union[Select, FromStatement], + key: Optional[_IdentityKeyType], + *, + load_options: Optional[Sequence[ORMOption]] = None, + refresh_state: Optional[InstanceState[Any]] = None, + with_for_update: Optional[ForUpdateArg] = None, + only_load_props: Optional[Iterable[str]] = None, + no_autoflush: bool = False, + bind_arguments: Mapping[str, Any] = util.EMPTY_DICT, + execution_options: _ExecuteOptions = util.EMPTY_DICT, + require_pk_cols: bool = False, + is_user_refresh: bool = False, +): + """Load the given identity key from the database.""" + if key is not None: + ident = key[1] + identity_token = key[2] + else: + ident = identity_token = None + + return load_on_pk_identity( + session, + statement, + ident, + load_options=load_options, + refresh_state=refresh_state, + with_for_update=with_for_update, + only_load_props=only_load_props, + identity_token=identity_token, + no_autoflush=no_autoflush, + bind_arguments=bind_arguments, + execution_options=execution_options, + require_pk_cols=require_pk_cols, + is_user_refresh=is_user_refresh, + ) + + +def load_on_pk_identity( + session: Session, + statement: Union[Select, FromStatement], + primary_key_identity: Optional[Tuple[Any, ...]], + *, + load_options: Optional[Sequence[ORMOption]] = None, + refresh_state: Optional[InstanceState[Any]] = None, + with_for_update: Optional[ForUpdateArg] = None, + only_load_props: Optional[Iterable[str]] = None, + identity_token: Optional[Any] = None, + no_autoflush: bool = False, + bind_arguments: Mapping[str, Any] = util.EMPTY_DICT, + execution_options: _ExecuteOptions = util.EMPTY_DICT, + require_pk_cols: bool = False, + is_user_refresh: bool = False, +): + """Load the given primary key identity from the database.""" + + query = statement + q = query._clone() + + assert not q._is_lambda_element + + if load_options is None: + load_options = QueryContext.default_load_options + + if ( + statement._compile_options + is SelectState.default_select_compile_options + ): + compile_options = ORMCompileState.default_compile_options + else: + compile_options = statement._compile_options + + if primary_key_identity is not None: + mapper = query._propagate_attrs["plugin_subject"] + + (_get_clause, _get_params) = mapper._get_clause + + # None present in ident - turn those comparisons + # into "IS NULL" + if None in primary_key_identity: + nones = { + _get_params[col].key + for col, value in zip(mapper.primary_key, primary_key_identity) + if value is None + } + + _get_clause = sql_util.adapt_criterion_to_null(_get_clause, nones) + + if len(nones) == len(primary_key_identity): + util.warn( + "fully NULL primary key identity cannot load any " + "object. This condition may raise an error in a future " + "release." + ) + + q._where_criteria = ( + sql_util._deep_annotate(_get_clause, {"_orm_adapt": True}), + ) + + params = { + _get_params[primary_key].key: id_val + for id_val, primary_key in zip( + primary_key_identity, mapper.primary_key + ) + } + else: + params = None + + if with_for_update is not None: + version_check = True + q._for_update_arg = with_for_update + elif query._for_update_arg is not None: + version_check = True + q._for_update_arg = query._for_update_arg + else: + version_check = False + + if require_pk_cols and only_load_props: + if not refresh_state: + raise sa_exc.ArgumentError( + "refresh_state is required when require_pk_cols is present" + ) + + refresh_state_prokeys = refresh_state.mapper._primary_key_propkeys + has_changes = { + key + for key in refresh_state_prokeys.difference(only_load_props) + if refresh_state.attrs[key].history.has_changes() + } + if has_changes: + # raise if pending pk changes are present. + # technically, this could be limited to the case where we have + # relationships in the only_load_props collection to be refreshed + # also (and only ones that have a secondary eager loader, at that). + # however, the error is in place across the board so that behavior + # here is easier to predict. The use case it prevents is one + # of mutating PK attrs, leaving them unflushed, + # calling session.refresh(), and expecting those attrs to remain + # still unflushed. It seems likely someone doing all those + # things would be better off having the PK attributes flushed + # to the database before tinkering like that (session.refresh() is + # tinkering). + raise sa_exc.InvalidRequestError( + f"Please flush pending primary key changes on " + "attributes " + f"{has_changes} for mapper {refresh_state.mapper} before " + "proceeding with a refresh" + ) + + # overall, the ORM has no internal flow right now for "dont load the + # primary row of an object at all, but fire off + # selectinload/subqueryload/immediateload for some relationships". + # It would probably be a pretty big effort to add such a flow. So + # here, the case for #8703 is introduced; user asks to refresh some + # relationship attributes only which are + # selectinload/subqueryload/immediateload/ etc. (not joinedload). + # ORM complains there's no columns in the primary row to load. + # So here, we just add the PK cols if that + # case is detected, so that there is a SELECT emitted for the primary + # row. + # + # Let's just state right up front, for this one little case, + # the ORM here is adding a whole extra SELECT just to satisfy + # limitations in the internal flow. This is really not a thing + # SQLAlchemy finds itself doing like, ever, obviously, we are + # constantly working to *remove* SELECTs we don't need. We + # rationalize this for now based on 1. session.refresh() is not + # commonly used 2. session.refresh() with only relationship attrs is + # even less commonly used 3. the SELECT in question is very low + # latency. + # + # to add the flow to not include the SELECT, the quickest way + # might be to just manufacture a single-row result set to send off to + # instances(), but we'd have to weave that into context.py and all + # that. For 2.0.0, we have enough big changes to navigate for now. + # + mp = refresh_state.mapper._props + for p in only_load_props: + if mp[p]._is_relationship: + only_load_props = refresh_state_prokeys.union(only_load_props) + break + + if refresh_state and refresh_state.load_options: + compile_options += {"_current_path": refresh_state.load_path.parent} + q = q.options(*refresh_state.load_options) + + new_compile_options, load_options = _set_get_options( + compile_options, + load_options, + version_check=version_check, + only_load_props=only_load_props, + refresh_state=refresh_state, + identity_token=identity_token, + is_user_refresh=is_user_refresh, + ) + + q._compile_options = new_compile_options + q._order_by = None + + if no_autoflush: + load_options += {"_autoflush": False} + + execution_options = util.EMPTY_DICT.merge_with( + execution_options, {"_sa_orm_load_options": load_options} + ) + result = ( + session.execute( + q, + params=params, + execution_options=execution_options, + bind_arguments=bind_arguments, + ) + .unique() + .scalars() + ) + + try: + return result.one() + except orm_exc.NoResultFound: + return None + + +def _set_get_options( + compile_opt, + load_opt, + populate_existing=None, + version_check=None, + only_load_props=None, + refresh_state=None, + identity_token=None, + is_user_refresh=None, +): + compile_options = {} + load_options = {} + if version_check: + load_options["_version_check"] = version_check + if populate_existing: + load_options["_populate_existing"] = populate_existing + if refresh_state: + load_options["_refresh_state"] = refresh_state + compile_options["_for_refresh_state"] = True + if only_load_props: + compile_options["_only_load_props"] = frozenset(only_load_props) + if identity_token: + load_options["_identity_token"] = identity_token + + if is_user_refresh: + load_options["_is_user_refresh"] = is_user_refresh + if load_options: + load_opt += load_options + if compile_options: + compile_opt += compile_options + + return compile_opt, load_opt + + +def _setup_entity_query( + compile_state, + mapper, + query_entity, + path, + adapter, + column_collection, + with_polymorphic=None, + only_load_props=None, + polymorphic_discriminator=None, + **kw, +): + if with_polymorphic: + poly_properties = mapper._iterate_polymorphic_properties( + with_polymorphic + ) + else: + poly_properties = mapper._polymorphic_properties + + quick_populators = {} + + path.set(compile_state.attributes, "memoized_setups", quick_populators) + + # for the lead entities in the path, e.g. not eager loads, and + # assuming a user-passed aliased class, e.g. not a from_self() or any + # implicit aliasing, don't add columns to the SELECT that aren't + # in the thing that's aliased. + check_for_adapt = adapter and len(path) == 1 and path[-1].is_aliased_class + + for value in poly_properties: + if only_load_props and value.key not in only_load_props: + continue + value.setup( + compile_state, + query_entity, + path, + adapter, + only_load_props=only_load_props, + column_collection=column_collection, + memoized_populators=quick_populators, + check_for_adapt=check_for_adapt, + **kw, + ) + + if ( + polymorphic_discriminator is not None + and polymorphic_discriminator is not mapper.polymorphic_on + ): + if adapter: + pd = adapter.columns[polymorphic_discriminator] + else: + pd = polymorphic_discriminator + column_collection.append(pd) + + +def _warn_for_runid_changed(state): + util.warn( + "Loading context for %s has changed within a load/refresh " + "handler, suggesting a row refresh operation took place. If this " + "event handler is expected to be " + "emitting row refresh operations within an existing load or refresh " + "operation, set restore_load_context=True when establishing the " + "listener to ensure the context remains unchanged when the event " + "handler completes." % (state_str(state),) + ) + + +def _instance_processor( + query_entity, + mapper, + context, + result, + path, + adapter, + only_load_props=None, + refresh_state=None, + polymorphic_discriminator=None, + _polymorphic_from=None, +): + """Produce a mapper level row processor callable + which processes rows into mapped instances.""" + + # note that this method, most of which exists in a closure + # called _instance(), resists being broken out, as + # attempts to do so tend to add significant function + # call overhead. _instance() is the most + # performance-critical section in the whole ORM. + + identity_class = mapper._identity_class + compile_state = context.compile_state + + # look for "row getter" functions that have been assigned along + # with the compile state that were cached from a previous load. + # these are operator.itemgetter() objects that each will extract a + # particular column from each row. + + getter_key = ("getters", mapper) + getters = path.get(compile_state.attributes, getter_key, None) + + if getters is None: + # no getters, so go through a list of attributes we are loading for, + # and the ones that are column based will have already put information + # for us in another collection "memoized_setups", which represents the + # output of the LoaderStrategy.setup_query() method. We can just as + # easily call LoaderStrategy.create_row_processor for each, but by + # getting it all at once from setup_query we save another method call + # per attribute. + props = mapper._prop_set + if only_load_props is not None: + props = props.intersection( + mapper._props[k] for k in only_load_props + ) + + quick_populators = path.get( + context.attributes, "memoized_setups", EMPTY_DICT + ) + + todo = [] + cached_populators = { + "new": [], + "quick": [], + "deferred": [], + "expire": [], + "existing": [], + "eager": [], + } + + if refresh_state is None: + # we can also get the "primary key" tuple getter function + pk_cols = mapper.primary_key + + if adapter: + pk_cols = [adapter.columns[c] for c in pk_cols] + primary_key_getter = result._tuple_getter(pk_cols) + else: + primary_key_getter = None + + getters = { + "cached_populators": cached_populators, + "todo": todo, + "primary_key_getter": primary_key_getter, + } + for prop in props: + if prop in quick_populators: + # this is an inlined path just for column-based attributes. + col = quick_populators[prop] + if col is _DEFER_FOR_STATE: + cached_populators["new"].append( + (prop.key, prop._deferred_column_loader) + ) + elif col is _SET_DEFERRED_EXPIRED: + # note that in this path, we are no longer + # searching in the result to see if the column might + # be present in some unexpected way. + cached_populators["expire"].append((prop.key, False)) + elif col is _RAISE_FOR_STATE: + cached_populators["new"].append( + (prop.key, prop._raise_column_loader) + ) + else: + getter = None + if adapter: + # this logic had been removed for all 1.4 releases + # up until 1.4.18; the adapter here is particularly + # the compound eager adapter which isn't accommodated + # in the quick_populators right now. The "fallback" + # logic below instead took over in many more cases + # until issue #6596 was identified. + + # note there is still an issue where this codepath + # produces no "getter" for cases where a joined-inh + # mapping includes a labeled column property, meaning + # KeyError is caught internally and we fall back to + # _getter(col), which works anyway. The adapter + # here for joined inh without any aliasing might not + # be useful. Tests which see this include + # test.orm.inheritance.test_basic -> + # EagerTargetingTest.test_adapt_stringency + # OptimizedLoadTest.test_column_expression_joined + # PolymorphicOnNotLocalTest.test_polymorphic_on_column_prop # noqa: E501 + # + + adapted_col = adapter.columns[col] + if adapted_col is not None: + getter = result._getter(adapted_col, False) + if not getter: + getter = result._getter(col, False) + if getter: + cached_populators["quick"].append((prop.key, getter)) + else: + # fall back to the ColumnProperty itself, which + # will iterate through all of its columns + # to see if one fits + prop.create_row_processor( + context, + query_entity, + path, + mapper, + result, + adapter, + cached_populators, + ) + else: + # loader strategies like subqueryload, selectinload, + # joinedload, basically relationships, these need to interact + # with the context each time to work correctly. + todo.append(prop) + + path.set(compile_state.attributes, getter_key, getters) + + cached_populators = getters["cached_populators"] + + populators = {key: list(value) for key, value in cached_populators.items()} + for prop in getters["todo"]: + prop.create_row_processor( + context, query_entity, path, mapper, result, adapter, populators + ) + + propagated_loader_options = context.propagated_loader_options + load_path = ( + context.compile_state.current_path + path + if context.compile_state.current_path.path + else path + ) + + session_identity_map = context.session.identity_map + + populate_existing = context.populate_existing or mapper.always_refresh + load_evt = bool(mapper.class_manager.dispatch.load) + refresh_evt = bool(mapper.class_manager.dispatch.refresh) + persistent_evt = bool(context.session.dispatch.loaded_as_persistent) + if persistent_evt: + loaded_as_persistent = context.session.dispatch.loaded_as_persistent + instance_state = attributes.instance_state + instance_dict = attributes.instance_dict + session_id = context.session.hash_key + runid = context.runid + identity_token = context.identity_token + + version_check = context.version_check + if version_check: + version_id_col = mapper.version_id_col + if version_id_col is not None: + if adapter: + version_id_col = adapter.columns[version_id_col] + version_id_getter = result._getter(version_id_col) + else: + version_id_getter = None + + if not refresh_state and _polymorphic_from is not None: + key = ("loader", path.path) + + if key in context.attributes and context.attributes[key].strategy == ( + ("selectinload_polymorphic", True), + ): + option_entities = context.attributes[key].local_opts["entities"] + else: + option_entities = None + selectin_load_via = mapper._should_selectin_load( + option_entities, + _polymorphic_from, + ) + + if selectin_load_via and selectin_load_via is not _polymorphic_from: + # only_load_props goes w/ refresh_state only, and in a refresh + # we are a single row query for the exact entity; polymorphic + # loading does not apply + assert only_load_props is None + + if selectin_load_via.is_mapper: + _load_supers = [] + _endmost_mapper = selectin_load_via + while ( + _endmost_mapper + and _endmost_mapper is not _polymorphic_from + ): + _load_supers.append(_endmost_mapper) + _endmost_mapper = _endmost_mapper.inherits + else: + _load_supers = [selectin_load_via] + + for _selectinload_entity in _load_supers: + if PostLoad.path_exists( + context, load_path, _selectinload_entity + ): + continue + callable_ = _load_subclass_via_in( + context, + path, + _selectinload_entity, + _polymorphic_from, + option_entities, + ) + PostLoad.callable_for_path( + context, + load_path, + _selectinload_entity.mapper, + _selectinload_entity, + callable_, + _selectinload_entity, + ) + + post_load = PostLoad.for_context(context, load_path, only_load_props) + + if refresh_state: + refresh_identity_key = refresh_state.key + if refresh_identity_key is None: + # super-rare condition; a refresh is being called + # on a non-instance-key instance; this is meant to only + # occur within a flush() + refresh_identity_key = mapper._identity_key_from_state( + refresh_state + ) + else: + refresh_identity_key = None + + primary_key_getter = getters["primary_key_getter"] + + if mapper.allow_partial_pks: + is_not_primary_key = _none_set.issuperset + else: + is_not_primary_key = _none_set.intersection + + def _instance(row): + # determine the state that we'll be populating + if refresh_identity_key: + # fixed state that we're refreshing + state = refresh_state + instance = state.obj() + dict_ = instance_dict(instance) + isnew = state.runid != runid + currentload = True + loaded_instance = False + else: + # look at the row, see if that identity is in the + # session, or we have to create a new one + identitykey = ( + identity_class, + primary_key_getter(row), + identity_token, + ) + + instance = session_identity_map.get(identitykey) + + if instance is not None: + # existing instance + state = instance_state(instance) + dict_ = instance_dict(instance) + + isnew = state.runid != runid + currentload = not isnew + loaded_instance = False + + if version_check and version_id_getter and not currentload: + _validate_version_id( + mapper, state, dict_, row, version_id_getter + ) + + else: + # create a new instance + + # check for non-NULL values in the primary key columns, + # else no entity is returned for the row + if is_not_primary_key(identitykey[1]): + return None + + isnew = True + currentload = True + loaded_instance = True + + instance = mapper.class_manager.new_instance() + + dict_ = instance_dict(instance) + state = instance_state(instance) + state.key = identitykey + state.identity_token = identity_token + + # attach instance to session. + state.session_id = session_id + session_identity_map._add_unpresent(state, identitykey) + + effective_populate_existing = populate_existing + if refresh_state is state: + effective_populate_existing = True + + # populate. this looks at whether this state is new + # for this load or was existing, and whether or not this + # row is the first row with this identity. + if currentload or effective_populate_existing: + # full population routines. Objects here are either + # just created, or we are doing a populate_existing + + # be conservative about setting load_path when populate_existing + # is in effect; want to maintain options from the original + # load. see test_expire->test_refresh_maintains_deferred_options + if isnew and ( + propagated_loader_options or not effective_populate_existing + ): + state.load_options = propagated_loader_options + state.load_path = load_path + + _populate_full( + context, + row, + state, + dict_, + isnew, + load_path, + loaded_instance, + effective_populate_existing, + populators, + ) + + if isnew: + # state.runid should be equal to context.runid / runid + # here, however for event checks we are being more conservative + # and checking against existing run id + # assert state.runid == runid + + existing_runid = state.runid + + if loaded_instance: + if load_evt: + state.manager.dispatch.load(state, context) + if state.runid != existing_runid: + _warn_for_runid_changed(state) + if persistent_evt: + loaded_as_persistent(context.session, state) + if state.runid != existing_runid: + _warn_for_runid_changed(state) + elif refresh_evt: + state.manager.dispatch.refresh( + state, context, only_load_props + ) + if state.runid != runid: + _warn_for_runid_changed(state) + + if effective_populate_existing or state.modified: + if refresh_state and only_load_props: + state._commit(dict_, only_load_props) + else: + state._commit_all(dict_, session_identity_map) + + if post_load: + post_load.add_state(state, True) + + else: + # partial population routines, for objects that were already + # in the Session, but a row matches them; apply eager loaders + # on existing objects, etc. + unloaded = state.unloaded + isnew = state not in context.partials + + if not isnew or unloaded or populators["eager"]: + # state is having a partial set of its attributes + # refreshed. Populate those attributes, + # and add to the "context.partials" collection. + + to_load = _populate_partial( + context, + row, + state, + dict_, + isnew, + load_path, + unloaded, + populators, + ) + + if isnew: + if refresh_evt: + existing_runid = state.runid + state.manager.dispatch.refresh(state, context, to_load) + if state.runid != existing_runid: + _warn_for_runid_changed(state) + + state._commit(dict_, to_load) + + if post_load and context.invoke_all_eagers: + post_load.add_state(state, False) + + return instance + + if mapper.polymorphic_map and not _polymorphic_from and not refresh_state: + # if we are doing polymorphic, dispatch to a different _instance() + # method specific to the subclass mapper + def ensure_no_pk(row): + identitykey = ( + identity_class, + primary_key_getter(row), + identity_token, + ) + if not is_not_primary_key(identitykey[1]): + return identitykey + else: + return None + + _instance = _decorate_polymorphic_switch( + _instance, + context, + query_entity, + mapper, + result, + path, + polymorphic_discriminator, + adapter, + ensure_no_pk, + ) + + return _instance + + +def _load_subclass_via_in( + context, path, entity, polymorphic_from, option_entities +): + mapper = entity.mapper + + # TODO: polymorphic_from seems to be a Mapper in all cases. + # this is likely not needed, but as we dont have typing in loading.py + # yet, err on the safe side + polymorphic_from_mapper = polymorphic_from.mapper + not_against_basemost = polymorphic_from_mapper.inherits is not None + + zero_idx = len(mapper.base_mapper.primary_key) == 1 + + if entity.is_aliased_class or not_against_basemost: + q, enable_opt, disable_opt = mapper._subclass_load_via_in( + entity, polymorphic_from + ) + else: + q, enable_opt, disable_opt = mapper._subclass_load_via_in_mapper + + def do_load(context, path, states, load_only, effective_entity): + if not option_entities: + # filter out states for those that would have selectinloaded + # from another loader + # TODO: we are currently ignoring the case where the + # "selectin_polymorphic" option is used, as this is much more + # complex / specific / very uncommon API use + states = [ + (s, v) + for s, v in states + if s.mapper._would_selectin_load_only_from_given_mapper(mapper) + ] + + if not states: + return + + orig_query = context.query + + if path.parent: + enable_opt_lcl = enable_opt._prepend_path(path) + disable_opt_lcl = disable_opt._prepend_path(path) + else: + enable_opt_lcl = enable_opt + disable_opt_lcl = disable_opt + options = ( + (enable_opt_lcl,) + orig_query._with_options + (disable_opt_lcl,) + ) + + q2 = q.options(*options) + + q2._compile_options = context.compile_state.default_compile_options + q2._compile_options += {"_current_path": path.parent} + + if context.populate_existing: + q2 = q2.execution_options(populate_existing=True) + + while states: + chunk = states[0 : SelectInLoader._chunksize] + states = states[SelectInLoader._chunksize :] + context.session.execute( + q2, + dict( + primary_keys=[ + state.key[1][0] if zero_idx else state.key[1] + for state, load_attrs in chunk + ] + ), + ).unique().scalars().all() + + return do_load + + +def _populate_full( + context, + row, + state, + dict_, + isnew, + load_path, + loaded_instance, + populate_existing, + populators, +): + if isnew: + # first time we are seeing a row with this identity. + state.runid = context.runid + + for key, getter in populators["quick"]: + dict_[key] = getter(row) + if populate_existing: + for key, set_callable in populators["expire"]: + dict_.pop(key, None) + if set_callable: + state.expired_attributes.add(key) + else: + for key, set_callable in populators["expire"]: + if set_callable: + state.expired_attributes.add(key) + + for key, populator in populators["new"]: + populator(state, dict_, row) + + elif load_path != state.load_path: + # new load path, e.g. object is present in more than one + # column position in a series of rows + state.load_path = load_path + + # if we have data, and the data isn't in the dict, OK, let's put + # it in. + for key, getter in populators["quick"]: + if key not in dict_: + dict_[key] = getter(row) + + # otherwise treat like an "already seen" row + for key, populator in populators["existing"]: + populator(state, dict_, row) + # TODO: allow "existing" populator to know this is + # a new path for the state: + # populator(state, dict_, row, new_path=True) + + else: + # have already seen rows with this identity in this same path. + for key, populator in populators["existing"]: + populator(state, dict_, row) + + # TODO: same path + # populator(state, dict_, row, new_path=False) + + +def _populate_partial( + context, row, state, dict_, isnew, load_path, unloaded, populators +): + if not isnew: + if unloaded: + # extra pass, see #8166 + for key, getter in populators["quick"]: + if key in unloaded: + dict_[key] = getter(row) + + to_load = context.partials[state] + for key, populator in populators["existing"]: + if key in to_load: + populator(state, dict_, row) + else: + to_load = unloaded + context.partials[state] = to_load + + for key, getter in populators["quick"]: + if key in to_load: + dict_[key] = getter(row) + for key, set_callable in populators["expire"]: + if key in to_load: + dict_.pop(key, None) + if set_callable: + state.expired_attributes.add(key) + for key, populator in populators["new"]: + if key in to_load: + populator(state, dict_, row) + + for key, populator in populators["eager"]: + if key not in unloaded: + populator(state, dict_, row) + + return to_load + + +def _validate_version_id(mapper, state, dict_, row, getter): + if mapper._get_state_attr_by_column( + state, dict_, mapper.version_id_col + ) != getter(row): + raise orm_exc.StaleDataError( + "Instance '%s' has version id '%s' which " + "does not match database-loaded version id '%s'." + % ( + state_str(state), + mapper._get_state_attr_by_column( + state, dict_, mapper.version_id_col + ), + getter(row), + ) + ) + + +def _decorate_polymorphic_switch( + instance_fn, + context, + query_entity, + mapper, + result, + path, + polymorphic_discriminator, + adapter, + ensure_no_pk, +): + if polymorphic_discriminator is not None: + polymorphic_on = polymorphic_discriminator + else: + polymorphic_on = mapper.polymorphic_on + if polymorphic_on is None: + return instance_fn + + if adapter: + polymorphic_on = adapter.columns[polymorphic_on] + + def configure_subclass_mapper(discriminator): + try: + sub_mapper = mapper.polymorphic_map[discriminator] + except KeyError: + raise AssertionError( + "No such polymorphic_identity %r is defined" % discriminator + ) + else: + if sub_mapper is mapper: + return None + elif not sub_mapper.isa(mapper): + return False + + return _instance_processor( + query_entity, + sub_mapper, + context, + result, + path, + adapter, + _polymorphic_from=mapper, + ) + + polymorphic_instances = util.PopulateDict(configure_subclass_mapper) + + getter = result._getter(polymorphic_on) + + def polymorphic_instance(row): + discriminator = getter(row) + if discriminator is not None: + _instance = polymorphic_instances[discriminator] + if _instance: + return _instance(row) + elif _instance is False: + identitykey = ensure_no_pk(row) + + if identitykey: + raise sa_exc.InvalidRequestError( + "Row with identity key %s can't be loaded into an " + "object; the polymorphic discriminator column '%s' " + "refers to %s, which is not a sub-mapper of " + "the requested %s" + % ( + identitykey, + polymorphic_on, + mapper.polymorphic_map[discriminator], + mapper, + ) + ) + else: + return None + else: + return instance_fn(row) + else: + identitykey = ensure_no_pk(row) + + if identitykey: + raise sa_exc.InvalidRequestError( + "Row with identity key %s can't be loaded into an " + "object; the polymorphic discriminator column '%s' is " + "NULL" % (identitykey, polymorphic_on) + ) + else: + return None + + return polymorphic_instance + + +class PostLoad: + """Track loaders and states for "post load" operations.""" + + __slots__ = "loaders", "states", "load_keys" + + def __init__(self): + self.loaders = {} + self.states = util.OrderedDict() + self.load_keys = None + + def add_state(self, state, overwrite): + # the states for a polymorphic load here are all shared + # within a single PostLoad object among multiple subtypes. + # Filtering of callables on a per-subclass basis needs to be done at + # the invocation level + self.states[state] = overwrite + + def invoke(self, context, path): + if not self.states: + return + path = path_registry.PathRegistry.coerce(path) + for ( + effective_context, + token, + limit_to_mapper, + loader, + arg, + kw, + ) in self.loaders.values(): + states = [ + (state, overwrite) + for state, overwrite in self.states.items() + if state.manager.mapper.isa(limit_to_mapper) + ] + if states: + loader( + effective_context, path, states, self.load_keys, *arg, **kw + ) + self.states.clear() + + @classmethod + def for_context(cls, context, path, only_load_props): + pl = context.post_load_paths.get(path.path) + if pl is not None and only_load_props: + pl.load_keys = only_load_props + return pl + + @classmethod + def path_exists(self, context, path, key): + return ( + path.path in context.post_load_paths + and key in context.post_load_paths[path.path].loaders + ) + + @classmethod + def callable_for_path( + cls, context, path, limit_to_mapper, token, loader_callable, *arg, **kw + ): + if path.path in context.post_load_paths: + pl = context.post_load_paths[path.path] + else: + pl = context.post_load_paths[path.path] = PostLoad() + pl.loaders[token] = ( + context, + token, + limit_to_mapper, + loader_callable, + arg, + kw, + ) + + +def load_scalar_attributes(mapper, state, attribute_names, passive): + """initiate a column-based attribute refresh operation.""" + + # assert mapper is _state_mapper(state) + session = state.session + if not session: + raise orm_exc.DetachedInstanceError( + "Instance %s is not bound to a Session; " + "attribute refresh operation cannot proceed" % (state_str(state)) + ) + + no_autoflush = bool(passive & attributes.NO_AUTOFLUSH) + + # in the case of inheritance, particularly concrete and abstract + # concrete inheritance, the class manager might have some keys + # of attributes on the superclass that we didn't actually map. + # These could be mapped as "concrete, don't load" or could be completely + # excluded from the mapping and we know nothing about them. Filter them + # here to prevent them from coming through. + if attribute_names: + attribute_names = attribute_names.intersection(mapper.attrs.keys()) + + if mapper.inherits and not mapper.concrete: + # load based on committed attributes in the object, formed into + # a truncated SELECT that only includes relevant tables. does not + # currently use state.key + statement = mapper._optimized_get_statement(state, attribute_names) + if statement is not None: + # undefer() isn't needed here because statement has the + # columns needed already, this implicitly undefers that column + stmt = FromStatement(mapper, statement) + + return load_on_ident( + session, + stmt, + None, + only_load_props=attribute_names, + refresh_state=state, + no_autoflush=no_autoflush, + ) + + # normal load, use state.key as the identity to SELECT + has_key = bool(state.key) + + if has_key: + identity_key = state.key + else: + # this codepath is rare - only valid when inside a flush, and the + # object is becoming persistent but hasn't yet been assigned + # an identity_key. + # check here to ensure we have the attrs we need. + pk_attrs = [ + mapper._columntoproperty[col].key for col in mapper.primary_key + ] + if state.expired_attributes.intersection(pk_attrs): + raise sa_exc.InvalidRequestError( + "Instance %s cannot be refreshed - it's not " + " persistent and does not " + "contain a full primary key." % state_str(state) + ) + identity_key = mapper._identity_key_from_state(state) + + if ( + _none_set.issubset(identity_key) and not mapper.allow_partial_pks + ) or _none_set.issuperset(identity_key): + util.warn_limited( + "Instance %s to be refreshed doesn't " + "contain a full primary key - can't be refreshed " + "(and shouldn't be expired, either).", + state_str(state), + ) + return + + result = load_on_ident( + session, + select(mapper).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL), + identity_key, + refresh_state=state, + only_load_props=attribute_names, + no_autoflush=no_autoflush, + ) + + # if instance is pending, a refresh operation + # may not complete (even if PK attributes are assigned) + if has_key and result is None: + raise orm_exc.ObjectDeletedError(state) diff --git a/python/user_packages/Python313/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7a4a3ea2424c09fbe48d455aed1eaa94d9124835 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..305989fcf0d03362d631f21b3178b84df0997a75 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02364b8f9dbaa0286fa103b283af4fca4da2da96 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/after.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/after.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1c4bb19d51e9e34fdf00c5014b3c455da5197c3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/after.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/before.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/before.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87689b03ed1113abc7c1f14ca83ae1d10e42885c Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/before.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/before_sleep.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/before_sleep.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c6db3665436b4e8c809e1d9d189f74461c3618 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/before_sleep.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/nap.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/nap.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81b7e3e1f5e0c1a094dee475aec0d54c3f93edb1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/nap.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/retry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9682cf58df50047fc4634ea55117f6412532840a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/retry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/stop.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/stop.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d597070964c0f7d6fb4c16f863f1329c20461f68 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/stop.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/tornadoweb.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/tornadoweb.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9355b999882887dc2c3e4a077d412ed007eddf72 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/tornadoweb.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/__pycache__/wait.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/__pycache__/wait.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2991f3351311bcaa44e84fe57aad7400b3270eea Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/__pycache__/wait.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/asyncio/__init__.py b/python/user_packages/Python313/site-packages/tenacity/asyncio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..230b115460b2e39d56bc3b6e3a19f079f4df5b7b --- /dev/null +++ b/python/user_packages/Python313/site-packages/tenacity/asyncio/__init__.py @@ -0,0 +1,210 @@ +# Copyright 2016 Étienne Bersac +# Copyright 2016 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import sys +import typing as t + +import tenacity +from tenacity import AttemptManager +from tenacity import BaseRetrying +from tenacity import DoAttempt +from tenacity import DoSleep +from tenacity import RetryCallState +from tenacity import RetryError +from tenacity import after_nothing +from tenacity import before_nothing +from tenacity import _utils + +# Import all built-in retry strategies for easier usage. +from .retry import RetryBaseT +from .retry import retry_all # noqa +from .retry import retry_any # noqa +from .retry import retry_if_exception # noqa +from .retry import retry_if_result # noqa +from ..retry import RetryBaseT as SyncRetryBaseT + +if t.TYPE_CHECKING: + from tenacity.stop import StopBaseT + from tenacity.wait import WaitBaseT + +WrappedFnReturnT = t.TypeVar("WrappedFnReturnT") +WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable[..., t.Awaitable[t.Any]]) + + +def _portable_async_sleep(seconds: float) -> t.Awaitable[None]: + # If trio is already imported, then importing it is cheap. + # If trio isn't already imported, then it's definitely not running, so we + # can skip further checks. + if "trio" in sys.modules: + # If trio is available, then sniffio is too + import trio + import sniffio + + if sniffio.current_async_library() == "trio": + return trio.sleep(seconds) + # Otherwise, assume asyncio + # Lazy import asyncio as it's expensive (responsible for 25-50% of total import overhead). + import asyncio + + return asyncio.sleep(seconds) + + +class AsyncRetrying(BaseRetrying): + def __init__( + self, + sleep: t.Callable[ + [t.Union[int, float]], t.Union[None, t.Awaitable[None]] + ] = _portable_async_sleep, + stop: "StopBaseT" = tenacity.stop.stop_never, + wait: "WaitBaseT" = tenacity.wait.wait_none(), + retry: "t.Union[SyncRetryBaseT, RetryBaseT]" = tenacity.retry_if_exception_type(), + before: t.Callable[ + ["RetryCallState"], t.Union[None, t.Awaitable[None]] + ] = before_nothing, + after: t.Callable[ + ["RetryCallState"], t.Union[None, t.Awaitable[None]] + ] = after_nothing, + before_sleep: t.Optional[ + t.Callable[["RetryCallState"], t.Union[None, t.Awaitable[None]]] + ] = None, + reraise: bool = False, + retry_error_cls: t.Type["RetryError"] = RetryError, + retry_error_callback: t.Optional[ + t.Callable[["RetryCallState"], t.Union[t.Any, t.Awaitable[t.Any]]] + ] = None, + ) -> None: + super().__init__( + sleep=sleep, # type: ignore[arg-type] + stop=stop, + wait=wait, + retry=retry, # type: ignore[arg-type] + before=before, # type: ignore[arg-type] + after=after, # type: ignore[arg-type] + before_sleep=before_sleep, # type: ignore[arg-type] + reraise=reraise, + retry_error_cls=retry_error_cls, + retry_error_callback=retry_error_callback, + ) + + async def __call__( # type: ignore[override] + self, fn: WrappedFn, *args: t.Any, **kwargs: t.Any + ) -> WrappedFnReturnT: + self.begin() + + retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs) + is_async = _utils.is_coroutine_callable(fn) + while True: + do = await self.iter(retry_state=retry_state) + if isinstance(do, DoAttempt): + try: + if is_async: + result = await fn(*args, **kwargs) + else: + result = fn(*args, **kwargs) + except BaseException: # noqa: B902 + retry_state.set_exception(sys.exc_info()) # type: ignore[arg-type] + else: + retry_state.set_result(result) + elif isinstance(do, DoSleep): + retry_state.prepare_for_next_attempt() + await self.sleep(do) # type: ignore[misc] + else: + return do # type: ignore[no-any-return] + + def _add_action_func(self, fn: t.Callable[..., t.Any]) -> None: + self.iter_state.actions.append(_utils.wrap_to_async_func(fn)) + + async def _run_retry(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + self.iter_state.retry_run_result = await _utils.wrap_to_async_func(self.retry)( + retry_state + ) + + async def _run_wait(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + if self.wait: + sleep = await _utils.wrap_to_async_func(self.wait)(retry_state) + else: + sleep = 0.0 + + retry_state.upcoming_sleep = sleep + + async def _run_stop(self, retry_state: "RetryCallState") -> None: # type: ignore[override] + self.statistics["delay_since_first_attempt"] = retry_state.seconds_since_start + self.iter_state.stop_run_result = await _utils.wrap_to_async_func(self.stop)( + retry_state + ) + + async def iter( + self, retry_state: "RetryCallState" + ) -> t.Union[DoAttempt, DoSleep, t.Any]: # noqa: A003 + self._begin_iter(retry_state) + result = None + for action in self.iter_state.actions: + result = await action(retry_state) + return result + + def __iter__(self) -> t.Generator[AttemptManager, None, None]: + raise TypeError("AsyncRetrying object is not iterable") + + def __aiter__(self) -> "AsyncRetrying": + self.begin() + self._retry_state = RetryCallState(self, fn=None, args=(), kwargs={}) + return self + + async def __anext__(self) -> AttemptManager: + while True: + do = await self.iter(retry_state=self._retry_state) + if do is None: + raise StopAsyncIteration + elif isinstance(do, DoAttempt): + return AttemptManager(retry_state=self._retry_state) + elif isinstance(do, DoSleep): + self._retry_state.prepare_for_next_attempt() + await self.sleep(do) # type: ignore[misc] + else: + raise StopAsyncIteration + + def wraps(self, fn: WrappedFn) -> WrappedFn: + wrapped = super().wraps(fn) + # Ensure wrapper is recognized as a coroutine function. + + @functools.wraps( + fn, functools.WRAPPER_ASSIGNMENTS + ("__defaults__", "__kwdefaults__") + ) + async def async_wrapped(*args: t.Any, **kwargs: t.Any) -> t.Any: + # Always create a copy to prevent overwriting the local contexts when + # calling the same wrapped functions multiple times in the same stack + copy = self.copy() + async_wrapped.statistics = copy.statistics # type: ignore[attr-defined] + return await copy(fn, *args, **kwargs) + + # Preserve attributes + async_wrapped.retry = self # type: ignore[attr-defined] + async_wrapped.retry_with = wrapped.retry_with # type: ignore[attr-defined] + async_wrapped.statistics = {} # type: ignore[attr-defined] + + return async_wrapped # type: ignore[return-value] + + +__all__ = [ + "retry_all", + "retry_any", + "retry_if_exception", + "retry_if_result", + "WrappedFn", + "AsyncRetrying", +] diff --git a/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a6a95fcee483ff517b3ddd0afdaa22d71939d51 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/retry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e11bc6cab2bdce135b3f456d8c06c52956e8c933 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tenacity/asyncio/__pycache__/retry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tenacity/asyncio/retry.py b/python/user_packages/Python313/site-packages/tenacity/asyncio/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..94b8b15428b9cdd85607e79ebb089af0fb70dd1b --- /dev/null +++ b/python/user_packages/Python313/site-packages/tenacity/asyncio/retry.py @@ -0,0 +1,125 @@ +# Copyright 2016–2021 Julien Danjou +# Copyright 2016 Joshua Harlow +# Copyright 2013-2014 Ray Holder +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import abc +import typing + +from tenacity import _utils +from tenacity import retry_base + +if typing.TYPE_CHECKING: + from tenacity import RetryCallState + + +class async_retry_base(retry_base): + """Abstract base class for async retry strategies.""" + + @abc.abstractmethod + async def __call__(self, retry_state: "RetryCallState") -> bool: # type: ignore[override] + pass + + def __and__( # type: ignore[override] + self, other: "typing.Union[retry_base, async_retry_base]" + ) -> "retry_all": + return retry_all(self, other) + + def __rand__( # type: ignore[misc,override] + self, other: "typing.Union[retry_base, async_retry_base]" + ) -> "retry_all": + return retry_all(other, self) + + def __or__( # type: ignore[override] + self, other: "typing.Union[retry_base, async_retry_base]" + ) -> "retry_any": + return retry_any(self, other) + + def __ror__( # type: ignore[misc,override] + self, other: "typing.Union[retry_base, async_retry_base]" + ) -> "retry_any": + return retry_any(other, self) + + +RetryBaseT = typing.Union[ + async_retry_base, typing.Callable[["RetryCallState"], typing.Awaitable[bool]] +] + + +class retry_if_exception(async_retry_base): + """Retry strategy that retries if an exception verifies a predicate.""" + + def __init__( + self, predicate: typing.Callable[[BaseException], typing.Awaitable[bool]] + ) -> None: + self.predicate = predicate + + async def __call__(self, retry_state: "RetryCallState") -> bool: # type: ignore[override] + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if retry_state.outcome.failed: + exception = retry_state.outcome.exception() + if exception is None: + raise RuntimeError("outcome failed but the exception is None") + return await self.predicate(exception) + else: + return False + + +class retry_if_result(async_retry_base): + """Retries if the result verifies a predicate.""" + + def __init__( + self, predicate: typing.Callable[[typing.Any], typing.Awaitable[bool]] + ) -> None: + self.predicate = predicate + + async def __call__(self, retry_state: "RetryCallState") -> bool: # type: ignore[override] + if retry_state.outcome is None: + raise RuntimeError("__call__() called before outcome was set") + + if not retry_state.outcome.failed: + return await self.predicate(retry_state.outcome.result()) + else: + return False + + +class retry_any(async_retry_base): + """Retries if any of the retries condition is valid.""" + + def __init__(self, *retries: typing.Union[retry_base, async_retry_base]) -> None: + self.retries = retries + + async def __call__(self, retry_state: "RetryCallState") -> bool: # type: ignore[override] + result = False + for r in self.retries: + result = result or await _utils.wrap_to_async_func(r)(retry_state) + if result: + break + return result + + +class retry_all(async_retry_base): + """Retries if all the retries condition are valid.""" + + def __init__(self, *retries: typing.Union[retry_base, async_retry_base]) -> None: + self.retries = retries + + async def __call__(self, retry_state: "RetryCallState") -> bool: # type: ignore[override] + result = True + for r in self.retries: + result = result and await _utils.wrap_to_async_func(r)(retry_state) + if not result: + break + return result diff --git a/python/user_packages/Python313/site-packages/tiktoken-0.12.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/tiktoken-0.12.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5dd575be1aa3628c682d11ce0a58a41af4850bd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tiktoken-0.12.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 OpenAI, Shantanu Jain + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0a7337948342ca3c5a2356211126dcfcdff265 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/_educational.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/_educational.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34fd4086768bd08fad0ad8662d822e9bfb19c423 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/_educational.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/core.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..054444993ad7fbcdbcc2fefd4b610a4fd63584ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/core.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/load.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/load.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85e9f46bd5b3677c19a1136a1f59f010de516c6f Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/load.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/model.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f3e4e0d4756980e34f8154780fbb61f05810017 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken/__pycache__/registry.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/registry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c25a2b4b815f15baeffb21c5dc1c2ec8b6e2ca1d Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken/__pycache__/registry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-313.pyc b/python/user_packages/Python313/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6f1bc1b2f5ef32843783a297941fae32b8960bf Binary files /dev/null and b/python/user_packages/Python313/site-packages/tiktoken_ext/__pycache__/openai_public.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers-0.23.1.dist-info/sboms/tokenizers-python.cyclonedx.json b/python/user_packages/Python313/site-packages/tokenizers-0.23.1.dist-info/sboms/tokenizers-python.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..cc5c6cb401e5913641594cac78c816a69d72d2eb --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers-0.23.1.dist-info/sboms/tokenizers-python.cyclonedx.json @@ -0,0 +1,4570 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:61f7eb37-bc31-4dee-b74a-b7c3ad55b3b6", + "metadata": { + "timestamp": "2026-04-27T14:39:54.553503800Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "authors": [ + { + "name": "Anthony MOI", + "email": "m.anthony.moi@gmail.com" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///D:/a/tokenizers/tokenizers/bindings/python#tokenizers-python@0.23.1", + "author": "Anthony MOI ", + "name": "tokenizers-python", + "version": "0.23.1", + "scope": "required", + "purl": "pkg:cargo/tokenizers-python@0.23.1?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///D:/a/tokenizers/tokenizers/bindings/python#tokenizers-python@0.23.1 bin-target-0", + "name": "tokenizers", + "version": "0.23.1", + "purl": "pkg:cargo/tokenizers-python@0.23.1?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "path+file:///D:/a/tokenizers/tokenizers/tokenizers#0.23.1", + "author": "Anthony MOI , Nicolas Patry ", + "name": "tokenizers", + "version": "0.23.1", + "description": "Provides an implementation of today's most used tokenizers, with a focus on performances and versatility. ", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/tokenizers@0.23.1?download_url=file://D:\\a\\tokenizers\\tokenizers\\tokenizers", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tokenizers/" + }, + { + "type": "website", + "url": "https://github.com/huggingface/tokenizers" + }, + { + "type": "vcs", + "url": "https://github.com/huggingface/tokenizers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "author": "Tom Kaitchuck ", + "name": "ahash", + "version": "0.8.12", + "description": "A non-cryptographic hash function using AES-NI for high performance", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ahash@0.8.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ahash" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/ahash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "author": "Andrew Gallant ", + "name": "aho-corasick", + "version": "1.1.4", + "description": "Fast multiple substring searching.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/aho-corasick@1.1.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/BurntSushi/aho-corasick" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/aho-corasick" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "name": "anstream", + "version": "1.0.0", + "description": "IO stream adapters for writing colored text that will gracefully degrade according to your terminal's capabilities.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstream@1.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "name": "anstyle-parse", + "version": "1.0.0", + "description": "Parse ANSI Style Escapes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-parse@1.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "name": "anstyle-query", + "version": "1.1.5", + "description": "Look up colored console capabilities", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-query@1.1.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "name": "anstyle-wincon", + "version": "3.0.11", + "description": "Styling legacy Windows terminals", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-wincon@3.0.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "name": "anstyle", + "version": "1.0.14", + "description": "ANSI text styling", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle@1.0.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "author": "Josh Stone ", + "name": "autocfg", + "version": "1.5.0", + "description": "Automatic cfg for Rust compiler features", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/autocfg@1.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/autocfg/" + }, + { + "type": "vcs", + "url": "https://github.com/cuviper/autocfg" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.13.1", + "author": "Alice Maz , Marshall Pierce ", + "name": "base64", + "version": "0.13.1", + "description": "encodes and decodes base64 as bytes or utf8", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/base64@0.13.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64" + }, + { + "type": "vcs", + "url": "https://github.com/marshallpierce/rust-base64" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1", + "author": "The Rust Project Developers", + "name": "bitflags", + "version": "2.11.1", + "description": "A macro to generate structures which behave like bitflags. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bitflags@2.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitflags" + }, + { + "type": "website", + "url": "https://github.com/bitflags/bitflags" + }, + { + "type": "vcs", + "url": "https://github.com/bitflags/bitflags" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "author": "Stephen M. Coakley ", + "name": "castaway", + "version": "0.2.4", + "description": "Safe, zero-cost downcasting for limited compile-time specialization.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/castaway@0.2.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sagebind/castaway" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.2.61", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.2.61", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.4", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5", + "name": "colorchoice", + "version": "1.0.5", + "description": "Global override of color control", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/colorchoice@1.0.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.9.0", + "author": "Parker Timmerman ", + "name": "compact_str", + "version": "0.9.0", + "description": "A memory efficient string type that transparently stores strings on the stack, when possible", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3fdb1325a1cece981e8a296ab8f0f9b63ae357bd0784a9faaf548cc7b480707a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/compact_str@0.9.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/ParkMyCar/compact_str" + }, + { + "type": "vcs", + "url": "https://github.com/ParkMyCar/compact_str" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#console@0.16.3", + "name": "console", + "version": "0.16.3", + "description": "A terminal and console abstraction for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/console@0.16.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/console" + }, + { + "type": "website", + "url": "https://github.com/console-rs/console" + }, + { + "type": "vcs", + "url": "https://github.com/console-rs/console" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "name": "crossbeam-deque", + "version": "0.8.6", + "description": "Concurrent work-stealing deque", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-deque@0.8.6", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "name": "crossbeam-epoch", + "version": "0.9.18", + "description": "Epoch-based garbage collection", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-epoch@0.9.18", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21", + "name": "crossbeam-utils", + "version": "0.8.21", + "description": "Utilities for concurrent programming", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-utils@0.8.21", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#daachorse@1.0.1", + "author": "Koichi Akabe , Shunsuke Kanda ", + "name": "daachorse", + "version": "1.0.1", + "description": "Daachorse: Double-Array Aho-Corasick", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6f55d7153ba3b507595872a3874803f07a8a81d1e888abed8e5db7da0597d6e2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/daachorse@1.0.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/daac-tools/daachorse" + }, + { + "type": "vcs", + "url": "https://github.com/daac-tools/daachorse" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "author": "Ted Driggs ", + "name": "darling", + "version": "0.20.11", + "description": "A proc-macro library for reading attributes into structs when implementing custom derives. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling@0.20.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/darling/0.20.11" + }, + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "author": "Ted Driggs ", + "name": "darling_core", + "version": "0.20.11", + "description": "Helper crate for proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_core@0.20.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11", + "author": "Ted Driggs ", + "name": "darling_macro", + "version": "0.20.11", + "description": "Internal support for a proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_macro@0.20.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dary_heap@0.3.9", + "author": "Han Mertens ", + "name": "dary_heap", + "version": "0.3.9", + "description": "A d-ary heap", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/dary_heap@0.3.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/hanmertens/dary_heap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder@0.20.2", + "author": "Colin Kiegel , Pascal Hertleif , Jan-Erik Rediger , Ted Driggs ", + "name": "derive_builder", + "version": "0.20.2", + "description": "Rust macro to automatically implement the builder pattern for arbitrary structs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/derive_builder@0.20.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/derive_builder/0.20.2" + }, + { + "type": "vcs", + "url": "https://github.com/colin-kiegel/rust-derive-builder" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder_core@0.20.2", + "author": "Colin Kiegel , Pascal Hertleif , Jan-Erik Rediger , Ted Driggs ", + "name": "derive_builder_core", + "version": "0.20.2", + "description": "Internal helper library for the derive_builder crate.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/derive_builder_core@0.20.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/derive_builder_core" + }, + { + "type": "vcs", + "url": "https://github.com/colin-kiegel/rust-derive-builder" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder_macro@0.20.2", + "author": "Colin Kiegel , Pascal Hertleif , Jan-Erik Rediger , Ted Driggs ", + "name": "derive_builder_macro", + "version": "0.20.2", + "description": "Rust macro to automatically implement the builder pattern for arbitrary structs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/derive_builder_macro@0.20.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/derive_builder_macro/0.20.2" + }, + { + "type": "vcs", + "url": "https://github.com/colin-kiegel/rust-derive-builder" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "author": "bluss", + "name": "either", + "version": "1.15.0", + "description": "The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/either@1.15.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/either/1/" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/either" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0", + "author": "Torbjørn Birch Moltu ", + "name": "encode_unicode", + "version": "1.0.0", + "description": "UTF-8 and UTF-16 character types, iterators and related methods for char, u8 and u16. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/encode_unicode@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/encode_unicode/" + }, + { + "type": "vcs", + "url": "https://github.com/tormol/encode_unicode" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#env_filter@1.0.1", + "name": "env_filter", + "version": "1.0.1", + "description": "Filter log events using environment variables ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/env_filter@1.0.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/env_logger" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#env_logger@0.11.10", + "name": "env_logger", + "version": "0.11.10", + "description": "A logging implementation for `log` which is configured via an environment variable. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/env_logger@0.11.10", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/env_logger" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#esaxx-rs@0.1.10", + "author": "Nicolas Patry ", + "name": "esaxx-rs", + "version": "0.1.10", + "description": "Wrapping around sentencepiece's esaxxx library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/esaxx-rs@0.1.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/esaxx-rs" + }, + { + "type": "website", + "url": "https://github.com/Narsil/esaxx-rs" + }, + { + "type": "vcs", + "url": "https://github.com/Narsil/esaxx-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "name": "find-msvc-tools", + "version": "0.1.9", + "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/find-msvc-tools@0.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/find-msvc-tools" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "author": "Alex Crichton ", + "name": "fnv", + "version": "1.0.7", + "description": "Fowler–Noll–Vo hash function", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/fnv@1.0.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://doc.servo.org/fnv/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-fnv" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "name": "futures-channel", + "version": "0.3.32", + "description": "Channels for asynchronous communication using futures-rs. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-channel@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "name": "futures-core", + "version": "0.3.32", + "description": "The core traits and types in for the `futures` library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-core@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "name": "futures-macro", + "version": "0.3.32", + "description": "The futures-rs procedural macro implementations. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-macro@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "name": "futures-task", + "version": "0.3.32", + "description": "Tools for working with tasks. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-task@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "name": "futures-util", + "version": "0.3.32", + "description": "Common utilities and extension traits for the futures-rs library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-util@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.3.4", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.3.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "name": "heck", + "version": "0.5.0", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "author": "Ted Driggs ", + "name": "ident_case", + "version": "1.0.1", + "description": "Utility for applying case rules to Rust identifiers.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ident_case@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ident_case/1.0.1" + }, + { + "type": "vcs", + "url": "https://github.com/TedDriggs/ident_case" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.18.4", + "name": "indicatif", + "version": "0.18.4", + "description": "A progress bar and cli reporting library for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/indicatif@0.18.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/indicatif" + }, + { + "type": "vcs", + "url": "https://github.com/console-rs/indicatif" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2", + "name": "is_terminal_polyfill", + "version": "1.70.2", + "description": "Polyfill for `is_terminal` stdlib feature for use with older MSRVs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/is_terminal_polyfill@1.70.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/polyfill-rs/is_terminal_polyfill" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "author": "bluss", + "name": "itertools", + "version": "0.14.0", + "description": "Extra iterator adaptors, iterator methods, free functions, and macros.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itertools@0.14.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itertools/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-itertools/itertools" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "author": "David Tolnay ", + "name": "itoa", + "version": "1.0.18", + "description": "Fast integer primitive to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itoa@1.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itoa" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/itoa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24", + "author": "Andrew Gallant ", + "name": "jiff", + "version": "0.2.24", + "description": "A date-time library that encourages you to jump into the pit of success. This library is heavily inspired by the Temporal project. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f00b5dbd620d61dfdcb6007c9c1f6054ebd75319f163d886a9055cec1155073d" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/jiff@0.2.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/jiff" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/jiff" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.186", + "description": "Raw FFI bindings to platform libraries like libc.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.186", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "author": "The Rust Project Developers", + "name": "log", + "version": "0.4.29", + "description": "A lightweight logging facade for Rust ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/log@0.4.29", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/log" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/log" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute-proc_macro@0.2.2", + "author": "Daniel Henry-Mantilla ", + "name": "macro_rules_attribute-proc_macro", + "version": "0.2.2", + "description": "Use declarative macros as proc_macro attributes or derives", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT OR Zlib" + } + ], + "purl": "pkg:cargo/macro_rules_attribute-proc_macro@0.2.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/danielhenrymantilla/macro_rules_attribute-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute@0.2.2", + "author": "Daniel Henry-Mantilla ", + "name": "macro_rules_attribute", + "version": "0.2.2", + "description": "Use declarative macros in attribute or derive position", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT OR Zlib" + } + ], + "purl": "pkg:cargo/macro_rules_attribute@0.2.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/macro_rules_attribute" + }, + { + "type": "website", + "url": "https://crates.io/crates/macro_rules_attribute" + }, + { + "type": "vcs", + "url": "https://github.com/danielhenrymantilla/macro_rules_attribute-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "author": "bluss, R. Janis Goldschmidt", + "name": "matrixmultiply", + "version": "0.3.10", + "description": "General matrix multiplication for f32 and f64 matrices. Operates on matrices with general layout (they can use arbitrary row and column stride). Detects and uses AVX or SSE2 on x86 platforms transparently for higher performance. Uses a microkernel strategy, so that the implementation is easy to parallelize and optimize. Supports multithreading.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/matrixmultiply@0.3.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/matrixmultiply/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/matrixmultiply/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "author": "Andrew Gallant , bluss", + "name": "memchr", + "version": "2.8.0", + "description": "Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for 1, 2 or 3 byte search and single substring search. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/memchr@2.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/memchr/" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/memchr" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/memchr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1", + "author": "Alex Huszagh ", + "name": "minimal-lexical", + "version": "0.2.1", + "description": "Fast float parsing conversion routines.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/minimal-lexical@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/minimal-lexical" + }, + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/minimal-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mio@1.2.0", + "author": "Carl Lerche , Thomas de Zeeuw , Tokio Contributors ", + "name": "mio", + "version": "1.2.0", + "description": "Lightweight non-blocking I/O.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/mio@1.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/mio" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/mio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#monostate-impl@0.1.18", + "author": "David Tolnay ", + "name": "monostate-impl", + "version": "0.1.18", + "description": "Implementation detail of the monostate crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/monostate-impl@0.1.18", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dtolnay/monostate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#monostate@0.1.18", + "author": "David Tolnay ", + "name": "monostate", + "version": "0.1.18", + "description": "Type that deserializes only from one specific value", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/monostate@0.1.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/monostate" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/monostate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.16.1", + "author": "Ulrik Sverdrup \"bluss\", Jim Turner", + "name": "ndarray", + "version": "0.16.1", + "description": "An n-dimensional array for general elements and for numerics. Lightweight array views and slicing; views support chunking and splitting.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ndarray@0.16.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ndarray/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-ndarray/ndarray" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "author": "Ulrik Sverdrup \"bluss\", Jim Turner", + "name": "ndarray", + "version": "0.17.2", + "description": "An n-dimensional array for general elements and for numerics. Lightweight array views and slicing; views support chunking and splitting.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ndarray@0.17.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ndarray/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-ndarray/ndarray" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3", + "author": "contact@geoffroycouprie.com", + "name": "nom", + "version": "7.1.3", + "description": "A byte-oriented, zero-copy, parser combinators library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nom@7.1.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/nom" + }, + { + "type": "vcs", + "url": "https://github.com/Geal/nom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "author": "The Rust Project Developers", + "name": "num-complex", + "version": "0.4.6", + "description": "Complex numbers implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-complex@0.4.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-complex" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-complex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-complex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "author": "The Rust Project Developers", + "name": "num-integer", + "version": "0.1.46", + "description": "Integer traits and functions", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-integer@0.1.46", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-integer" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-integer" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-integer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "author": "The Rust Project Developers", + "name": "num-traits", + "version": "0.2.19", + "description": "Numeric traits for generic mathematics", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-traits@0.2.19", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-traits" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-traits" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#numpy@0.28.0", + "author": "The rust-numpy Project Developers, PyO3 Project and Contributors ", + "name": "numpy", + "version": "0.28.0", + "description": "PyO3-based Rust bindings of the NumPy C-API", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "778da78c64ddc928ebf5ad9df5edf0789410ff3bdbf3619aed51cd789a6af1e2" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause" + } + ], + "purl": "pkg:cargo/numpy@0.28.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/numpy" + }, + { + "type": "vcs", + "url": "https://github.com/PyO3/rust-numpy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.4", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2", + "name": "once_cell_polyfill", + "version": "1.70.2", + "description": "Polyfill for `OnceCell` stdlib feature for use with older MSRVs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell_polyfill@1.70.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/polyfill-rs/once_cell_polyfill" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#onig@6.5.3", + "author": "Will Speak , Ivan Ivashchenko ", + "name": "onig", + "version": "6.5.3", + "description": "Rust-Onig is a set of Rust bindings for the Oniguruma regular expression library. Oniguruma is a modern regex library with support for multiple character encodings and regex syntaxes. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/onig@6.5.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/onig/" + }, + { + "type": "vcs", + "url": "https://github.com/iwillspeak/rust-onig" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#onig_sys@69.9.3", + "author": "Will Speak , Ivan Ivashchenko ", + "name": "onig_sys", + "version": "69.9.3", + "description": "The `onig_sys` crate contains raw rust bindings to the oniguruma library. This crate exposes a set of unsafe functions which can then be used by other crates to create safe wrappers around Oniguruma. You probably don't want to link to this crate directly; instead check out the `onig` crate. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/onig_sys@69.9.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/onig_sys" + }, + { + "type": "other", + "url": "onig" + }, + { + "type": "vcs", + "url": "https://github.com/rust-onig/rust-onig" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "author": "David Tolnay ", + "name": "paste", + "version": "1.0.15", + "description": "Macros for all your token pasting needs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/paste@1.0.15", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/paste" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/paste" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "name": "pin-project-lite", + "version": "0.2.17", + "description": "A lightweight version of pin-project written with declarative macros. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pin-project-lite@0.2.17", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/pin-project-lite" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33", + "author": "Alex Crichton ", + "name": "pkg-config", + "version": "0.3.33", + "description": "A library to run the pkg-config system tool at build time in order to be used in Cargo build scripts. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pkg-config@0.3.33", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pkg-config" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/pkg-config-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "name": "portable-atomic", + "version": "1.13.1", + "description": "Portable atomic types including support for 128-bit atomics, atomic float, etc. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/portable-atomic@1.13.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/portable-atomic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "author": "The CryptoCorrosion Contributors", + "name": "ppv-lite86", + "version": "0.2.21", + "description": "Cross-platform cryptography-oriented low-level SIMD library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ppv-lite86@0.2.21", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/cryptocorrosion/cryptocorrosion" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.106", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.106", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-async-runtimes@0.28.0", + "author": "Andrew J Westlake , David Hewitt ", + "name": "pyo3-async-runtimes", + "version": "0.28.0", + "description": "PyO3 bridges from Rust runtimes to Python's Asyncio library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9e7364a95bf00e8377bbf9b0f09d7ff9715a29d8fcf93b47d1a967363b973178" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-async-runtimes@0.28.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3-async-runtimes/" + }, + { + "type": "website", + "url": "https://github.com/PyO3/pyo3-async-runtimes" + }, + { + "type": "vcs", + "url": "https://github.com/PyO3/pyo3-async-runtimes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.28.2", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8bf94ee265674bf76c09fa430b0e99c26e319c945d96ca0d5a8215f31bf81cf7" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.28.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.28.2", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "491aa5fc66d8059dd44a75f4580a2962c1862a1c2945359db36f6c2818b748dc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.28.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros-backend", + "version": "0.28.2", + "description": "Code generation for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "22faaa1ce6c430a1f71658760497291065e6450d7b5dc2bcf254d49f66ee700a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros-backend@0.28.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros", + "version": "0.28.2", + "description": "Proc macros for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f5d671734e9d7a43449f8480f8b38115df67bef8d21f76837fa75ee7aaa5e52e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros@0.28.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3", + "version": "0.28.2", + "description": "Bindings to Python interpreter", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cf85e27e86080aafd5a22eae58a162e133a589551542b3e5cee4beb27e54f8e1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3@0.28.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3/" + }, + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.45", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.45", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.4", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand", + "version": "0.9.4", + "description": "Random number generators and other randomness functionality. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand@0.9.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "author": "The Rand Project Developers, The Rust Project Developers, The CryptoCorrosion Contributors", + "name": "rand_chacha", + "version": "0.9.0", + "description": "ChaCha random number generator ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_chacha@0.9.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_chacha" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand_core", + "version": "0.9.5", + "description": "Core random number generator traits and tools for implementation. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_core@0.9.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_core" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1", + "author": "bluss", + "name": "rawpointer", + "version": "0.2.1", + "description": "Extra methods for raw pointers and `NonNull`. For example `.post_inc()` and `.pre_dec()` (c.f. `ptr++` and `--ptr`), `offset` and `add` for `NonNull`, and the function `ptrdistance`. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rawpointer@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rawpointer/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/rawpointer/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-cond@0.4.0", + "author": "Josh Stone ", + "name": "rayon-cond", + "version": "0.4.0", + "description": "Experimental iterator wrapper that is conditionally parallel or serial.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/rayon-cond@0.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/cuviper/rayon-cond" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0", + "name": "rayon-core", + "version": "1.13.0", + "description": "Core APIs for Rayon", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rayon-core@1.13.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rayon-core/" + }, + { + "type": "other", + "url": "rayon-core" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/rayon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rayon@1.12.0", + "name": "rayon", + "version": "1.12.0", + "description": "Simple work-stealing parallelism for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rayon@1.12.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rayon/" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/rayon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-automata", + "version": "0.4.14", + "description": "Automata construction and matching using regular expressions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-automata@0.4.14", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-automata" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-automata" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-syntax", + "version": "0.8.10", + "description": "A regular expression parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-syntax@0.8.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-syntax" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-syntax" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex", + "version": "1.12.3", + "description": "An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex@1.12.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.2", + "author": "The Rust Project Developers", + "name": "rustc-hash", + "version": "2.1.2", + "description": "A speedy, non-cryptographic hashing algorithm used by rustc", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/rustc-hash@2.1.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/rustc-hash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "author": "David Tolnay ", + "name": "rustversion", + "version": "1.0.22", + "description": "Conditional compilation according to rustc compiler version", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustversion@1.0.22", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rustversion" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/rustversion" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "author": "David Tolnay ", + "name": "ryu", + "version": "1.0.23", + "description": "Fast floating point to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR BSL-1.0" + } + ], + "purl": "pkg:cargo/ryu@1.0.23", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ryu" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/ryu" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde", + "version": "1.0.228", + "description": "A generic serialization/deserialization framework", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_core", + "version": "1.0.228", + "description": "Serde traits only, with no support for derive -- use the `serde` crate instead", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_core@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_core" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_derive", + "version": "1.0.228", + "description": "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_derive@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://serde.rs/derive.html" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_json", + "version": "1.0.149", + "description": "A JSON serialization file format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_json@1.0.149", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_json" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/json" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0", + "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", + "name": "shlex", + "version": "1.3.0", + "description": "Split a string into shell words, like Python's shlex.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/shlex@1.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/comex/rust-shlex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "author": "Carl Lerche ", + "name": "slab", + "version": "0.4.12", + "description": "Pre-allocated storage for a uniform data type", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/slab@0.4.12", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/slab" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "author": "The Servo Project Developers", + "name": "smallvec", + "version": "1.15.1", + "description": "'Small vector' optimization: store up to a small number of items on the stack", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/smallvec@1.15.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/smallvec/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-smallvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#spm_precompiled@0.1.4", + "author": "Nicolas Patry ", + "name": "spm_precompiled", + "version": "0.1.4", + "description": "This crate aims to emulate https://github.com/google/sentencepiece Dart::DoubleArray struct and it's Normalizer. This crate is highly specialized and not intended for general use. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/spm_precompiled@0.1.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/spm_precompiled/" + }, + { + "type": "website", + "url": "https://github.com/huggingface/spm_precompiled" + }, + { + "type": "vcs", + "url": "https://github.com/huggingface/spm_precompiled" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0", + "author": "Nikolai Vazquez", + "name": "static_assertions", + "version": "1.1.0", + "description": "Compile-time assertions to ensure that invariants are met.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/static_assertions@1.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/static_assertions/" + }, + { + "type": "website", + "url": "https://github.com/nvzqz/static-assertions-rs" + }, + { + "type": "vcs", + "url": "https://github.com/nvzqz/static-assertions-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1", + "author": "Danny Guo , maxbachmann ", + "name": "strsim", + "version": "0.11.1", + "description": "Implementations of string similarity metrics. Includes Hamming, Levenshtein, OSA, Damerau-Levenshtein, Jaro, Jaro-Winkler, and Sørensen-Dice. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strsim@0.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strsim/" + }, + { + "type": "website", + "url": "https://github.com/rapidfuzz/strsim-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rapidfuzz/strsim-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.117", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.117", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.5", + "description": "LLVM target triple types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18", + "author": "David Tolnay ", + "name": "thiserror-impl", + "version": "2.0.18", + "description": "Implementation detail of the `thiserror` crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror-impl@2.0.18", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "author": "David Tolnay ", + "name": "thiserror", + "version": "2.0.18", + "description": "derive(Error)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror@2.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/thiserror" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.7.0", + "author": "Tokio Contributors ", + "name": "tokio-macros", + "version": "2.7.0", + "description": "Tokio's proc macros. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio-macros@2.7.0", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio@1.52.1", + "author": "Tokio Contributors ", + "name": "tokio", + "version": "1.52.1", + "description": "An event-driven, non-blocking I/O platform for writing asynchronous I/O backed applications. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio@1.52.1", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.24", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization-alignments@0.1.12", + "author": "Anthony MOI ", + "name": "unicode-normalization-alignments", + "version": "0.1.12", + "description": "This crate provides functions for normalization of Unicode strings, including Canonical and Compatible Decomposition and Recomposition, as described in Unicode Standard Annex #15. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-normalization-alignments@0.1.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-normalization-alignments/" + }, + { + "type": "website", + "url": "https://github.com/n1t0/unicode-normalization" + }, + { + "type": "vcs", + "url": "https://github.com/n1t0/unicode-normalization" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.13.2", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-segmentation", + "version": "1.13.2", + "description": "This crate provides Grapheme Cluster, Word and Sentence boundaries according to Unicode Standard Annex #29 rules. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-segmentation@1.13.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-segmentation" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-segmentation" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.2", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-width", + "version": "0.2.2", + "description": "Determine displayed width of `char` and `str` types according to Unicode Standard Annex #11 rules. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-width@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-width" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-width" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode_categories@0.1.1", + "author": "Sean Gillespie ", + "name": "unicode_categories", + "version": "0.1.1", + "description": "Query Unicode category membership for chars", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode_categories@0.1.1", + "externalReferences": [ + { + "type": "documentation", + "url": "http://swgillespie.github.io/unicode-categories/unicode_categories/" + }, + { + "type": "vcs", + "url": "https://github.com/swgillespie/unicode-categories" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unit-prefix@0.5.2", + "author": "Fabio Valentini , Benjamin Sago ", + "name": "unit-prefix", + "version": "0.5.2", + "description": "Format numbers with metric and binary unit prefixes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/unit-prefix@0.5.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://codeberg.org/commons-rs/unit-prefix" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2", + "author": "Joe Wilm , Christian Duerr ", + "name": "utf8parse", + "version": "0.2.2", + "description": "Table-driven UTF-8 parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/utf8parse@0.2.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf8parse/" + }, + { + "type": "vcs", + "url": "https://github.com/alacritty/vte" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "author": "Sergio Benitez ", + "name": "version_check", + "version": "0.9.5", + "description": "Tiny crate to check the version of the installed/running rustc.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/version_check@0.9.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/version_check/" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/version_check" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1", + "name": "windows-link", + "version": "0.2.1", + "description": "Linking for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-link@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2", + "name": "windows-sys", + "version": "0.61.2", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.61.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.48", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy", + "version": "0.8.48", + "description": "Zerocopy makes zero-cost memory manipulation effortless. We write \"unsafe\" so you don't have to.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy@0.8.48", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21", + "author": "David Tolnay ", + "name": "zmij", + "version": "1.0.21", + "description": "A double-to-string conversion algorithm based on Schubfach and yy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zmij@1.0.21", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/zmij" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/zmij" + } + ] + } + ], + "dependencies": [ + { + "ref": "path+file:///D:/a/tokenizers/tokenizers/bindings/python#tokenizers-python@0.23.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#env_logger@0.11.10", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.16.1", + "registry+https://github.com/rust-lang/crates.io-index#numpy@0.28.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-async-runtimes@0.28.0", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.12.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "path+file:///D:/a/tokenizers/tokenizers/tokenizers#0.23.1", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.52.1" + ] + }, + { + "ref": "path+file:///D:/a/tokenizers/tokenizers/tokenizers#0.23.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#daachorse@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#dary_heap@0.3.9", + "registry+https://github.com/rust-lang/crates.io-index#derive_builder@0.20.2", + "registry+https://github.com/rust-lang/crates.io-index#esaxx-rs@0.1.10", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.18.4", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#monostate@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#onig@6.5.3", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.4", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.12.0", + "registry+https://github.com/rust-lang/crates.io-index#rayon-cond@0.4.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#spm_precompiled@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization-alignments@0.1.12", + "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.13.2", + "registry+https://github.com/rust-lang/crates.io-index#unicode_categories@0.1.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.48" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2", + "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.13.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.9.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#console@0.16.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#daachorse@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dary_heap@0.3.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder@0.20.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#derive_builder_macro@0.20.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder_core@0.20.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_builder_macro@0.20.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#derive_builder_core@0.20.2", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#env_filter@1.0.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#env_logger@0.11.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#env_filter@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#esaxx-rs@0.1.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.18.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#console@0.16.3", + "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#unit-prefix@0.5.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#jiff@0.2.24", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute-proc_macro@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#macro_rules_attribute-proc_macro@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mio@1.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#monostate-impl@0.1.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#monostate@0.1.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#monostate-impl@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.16.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#numpy@0.28.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#onig@6.5.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#onig_sys@69.9.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#onig_sys@69.9.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.48" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-async-runtimes@0.28.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.52.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-cond@0.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.12.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rayon@1.12.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#spm_precompiled@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.13.1", + "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.13.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio@1.52.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#mio@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.7.0", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization-alignments@0.1.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.13.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode_categories@0.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unit-prefix@0.5.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.48" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + } + ] +} \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/tokenizers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9354f2de429e2939d43582308ea90caadee18b4a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/decoders/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/decoders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf42c8857f49955d727da350aab2599a12ac2873 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/decoders/__init__.py @@ -0,0 +1,15 @@ +from .. import decoders + + +Decoder = decoders.Decoder +ByteLevel = decoders.ByteLevel +Replace = decoders.Replace +WordPiece = decoders.WordPiece +ByteFallback = decoders.ByteFallback +Fuse = decoders.Fuse +Strip = decoders.Strip +Metaspace = decoders.Metaspace +BPEDecoder = decoders.BPEDecoder +CTC = decoders.CTC +Sequence = decoders.Sequence +DecodeStream = decoders.DecodeStream diff --git a/python/user_packages/Python313/site-packages/tokenizers/decoders/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/decoders/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4147630ea1234049ec3089206e3d3aefc8a37950 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/decoders/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..710505ed6627e3322ba06ad8547769b0934ff537 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/__init__.py @@ -0,0 +1,6 @@ +from .base_tokenizer import BaseTokenizer +from .bert_wordpiece import BertWordPieceTokenizer +from .byte_level_bpe import ByteLevelBPETokenizer +from .char_level_bpe import CharBPETokenizer +from .sentencepiece_bpe import SentencePieceBPETokenizer +from .sentencepiece_unigram import SentencePieceUnigramTokenizer diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14bfb685d83ec2de1de4f10f99ad145e6444792e Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/base_tokenizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/base_tokenizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e372b03cb21750677fce41a3d5b2199b929720d Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/base_tokenizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/bert_wordpiece.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/bert_wordpiece.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5adb7a4239843d66b59ccedd9e3f7252a0259e7a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/bert_wordpiece.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/byte_level_bpe.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/byte_level_bpe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa629cac454f98ab25eccd1afdbdd785595be41c Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/byte_level_bpe.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/char_level_bpe.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/char_level_bpe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2d3e9e90f4f7878d53fa148e5cd91c39002bd21 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/char_level_bpe.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b655dd94242dbff4b3277979a4a21e11dd08bc76 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_bpe.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae90c182625c619119b7e88f65de633cb7964138 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/implementations/__pycache__/sentencepiece_unigram.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/base_tokenizer.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/base_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..89f3e4d88b70344b75f1a6d69d623a9499edcab8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/base_tokenizer.py @@ -0,0 +1,477 @@ +from typing import Dict, List, Optional, Tuple, Union + +from tokenizers import AddedToken, EncodeInput, Encoding, InputSequence, Tokenizer +from tokenizers.decoders import Decoder +from tokenizers.models import Model +from tokenizers.normalizers import Normalizer +from tokenizers.pre_tokenizers import PreTokenizer +from tokenizers.processors import PostProcessor + + +Offsets = Tuple[int, int] + + +class BaseTokenizer: + def __init__(self, tokenizer: Tokenizer, parameters=None): + self._tokenizer = tokenizer + self._parameters = parameters if parameters is not None else {} + + def __repr__(self): + return "Tokenizer(vocabulary_size={}, {})".format( + self._tokenizer.get_vocab_size(), + ", ".join(k + "=" + str(v) for k, v in self._parameters.items()), + ) + + def num_special_tokens_to_add(self, is_pair: bool) -> int: + """ + Return the number of special tokens that would be added for single/pair sentences. + :param is_pair: Boolean indicating if the input would be a single sentence or a pair + :return: + """ + return self._tokenizer.num_special_tokens_to_add(is_pair) + + def get_vocab(self, with_added_tokens: bool = True) -> Dict[str, int]: + """Returns the vocabulary + + Args: + with_added_tokens: boolean: + Whether to include the added tokens in the vocabulary + + Returns: + The vocabulary + """ + return self._tokenizer.get_vocab(with_added_tokens=with_added_tokens) + + def get_added_tokens_decoder(self) -> Dict[int, AddedToken]: + """Returns the added reverse vocabulary + + Returns: + The added vocabulary mapping ints to AddedTokens + """ + return self._tokenizer.get_added_tokens_decoder() + + def get_vocab_size(self, with_added_tokens: bool = True) -> int: + """Return the size of vocabulary, with or without added tokens. + + Args: + with_added_tokens: (`optional`) bool: + Whether to count in added special tokens or not + + Returns: + Size of vocabulary + """ + return self._tokenizer.get_vocab_size(with_added_tokens=with_added_tokens) + + def enable_padding( + self, + direction: Optional[str] = "right", + pad_to_multiple_of: Optional[int] = None, + pad_id: Optional[int] = 0, + pad_type_id: Optional[int] = 0, + pad_token: Optional[str] = "[PAD]", + length: Optional[int] = None, + ): + """Change the padding strategy + + Args: + direction: (`optional`) str: + Can be one of: `right` or `left` + + pad_to_multiple_of: (`optional`) unsigned int: + If specified, the padding length should always snap to the next multiple of + the given value. For example if we were going to pad with a length of 250 but + `pad_to_multiple_of=8` then we will pad to 256. + + pad_id: (`optional`) unsigned int: + The indice to be used when padding + + pad_type_id: (`optional`) unsigned int: + The type indice to be used when padding + + pad_token: (`optional`) str: + The pad token to be used when padding + + length: (`optional`) unsigned int: + If specified, the length at which to pad. If not specified + we pad using the size of the longest sequence in a batch + """ + return self._tokenizer.enable_padding( + direction=direction, + pad_to_multiple_of=pad_to_multiple_of, + pad_id=pad_id, + pad_type_id=pad_type_id, + pad_token=pad_token, + length=length, + ) + + def no_padding(self): + """Disable padding""" + return self._tokenizer.no_padding() + + @property + def padding(self) -> Optional[dict]: + """Get the current padding parameters + + Returns: + None if padding is disabled, a dict with the currently set parameters + if the padding is enabled. + """ + return self._tokenizer.padding + + def enable_truncation(self, max_length: int, stride: Optional[int] = 0, strategy: Optional[str] = "longest_first"): + """Change the truncation options + + Args: + max_length: unsigned int: + The maximum length at which to truncate + + stride: (`optional`) unsigned int: + The length of the previous first sequence to be included + in the overflowing sequence + + strategy: (`optional`) str: + Can be one of `longest_first`, `only_first` or `only_second` + """ + return self._tokenizer.enable_truncation(max_length, stride=stride, strategy=strategy) + + def no_truncation(self): + """Disable truncation""" + return self._tokenizer.no_truncation() + + @property + def truncation(self) -> Optional[dict]: + """Get the current truncation parameters + + Returns: + None if truncation is disabled, a dict with the current truncation parameters if + truncation is enabled + """ + return self._tokenizer.truncation + + def add_tokens(self, tokens: List[Union[str, AddedToken]]) -> int: + """Add the given tokens to the vocabulary + + Args: + tokens: List[Union[str, AddedToken]]: + A list of tokens to add to the vocabulary. Each token can either be + a string, or an instance of AddedToken + + Returns: + The number of tokens that were added to the vocabulary + """ + return self._tokenizer.add_tokens(tokens) + + def add_special_tokens(self, special_tokens: List[Union[str, AddedToken]]) -> int: + """Add the given special tokens to the vocabulary, and treat them as special tokens. + + The special tokens will never be processed by the model, and will be + removed while decoding. + + Args: + tokens: List[Union[str, AddedToken]]: + A list of special tokens to add to the vocabulary. Each token can either be + a string, or an instance of AddedToken + + Returns: + The number of tokens that were added to the vocabulary + """ + return self._tokenizer.add_special_tokens(special_tokens) + + def normalize(self, sequence: str) -> str: + """Normalize the given sequence + + Args: + sequence: str: + The sequence to normalize + + Returns: + The normalized string + """ + return self._tokenizer.normalizer.normalize_str(sequence) + + def encode( + self, + sequence: InputSequence, + pair: Optional[InputSequence] = None, + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> Encoding: + """Encode the given sequence and pair. This method can process raw text sequences as well + as already pre-tokenized sequences. + + Args: + sequence: InputSequence: + The sequence we want to encode. This sequence can be either raw text or + pre-tokenized, according to the `is_pretokenized` argument: + + - If `is_pretokenized=False`: `InputSequence` is expected to be `str` + - If `is_pretokenized=True`: `InputSequence` is expected to be + `Union[List[str], Tuple[str]]` + + is_pretokenized: bool: + Whether the input is already pre-tokenized. + + add_special_tokens: bool: + Whether to add the special tokens while encoding. + + Returns: + An Encoding + """ + if sequence is None: + raise ValueError("encode: `sequence` can't be `None`") + + return self._tokenizer.encode(sequence, pair, is_pretokenized, add_special_tokens) + + def encode_batch( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Encode the given inputs. This method accept both raw text sequences as well as already + pre-tokenized sequences. + + Args: + inputs: List[EncodeInput]: + A list of single sequences or pair sequences to encode. Each `EncodeInput` is + expected to be of the following form: + `Union[InputSequence, Tuple[InputSequence, InputSequence]]` + + Each `InputSequence` can either be raw text or pre-tokenized, + according to the `is_pretokenized` argument: + + - If `is_pretokenized=False`: `InputSequence` is expected to be `str` + - If `is_pretokenized=True`: `InputSequence` is expected to be + `Union[List[str], Tuple[str]]` + + is_pretokenized: bool: + Whether the input is already pre-tokenized. + + add_special_tokens: bool: + Whether to add the special tokens while encoding. + + Returns: + A list of Encoding + """ + + if inputs is None: + raise ValueError("encode_batch: `inputs` can't be `None`") + + return self._tokenizer.encode_batch(inputs, is_pretokenized, add_special_tokens) + + async def async_encode_batch( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Asynchronously encode a batch (tracks character offsets). + + Args: + inputs: A list of single or pair sequences to encode. + is_pretokenized: Whether inputs are already pre-tokenized. + add_special_tokens: Whether to add special tokens. + + Returns: + A list of Encoding. + """ + if inputs is None: + raise ValueError("async_encode_batch: `inputs` can't be `None`") + # Exposed by the Rust bindings via pyo3_async_runtimes::tokio::future_into_py + return await self._tokenizer.async_encode_batch(inputs, is_pretokenized, add_special_tokens) + + async def async_encode_batch_fast( + self, + inputs: List[EncodeInput], + is_pretokenized: bool = False, + add_special_tokens: bool = True, + ) -> List[Encoding]: + """Asynchronously encode a batch (no character offsets, faster). + + Args: + inputs: A list of single or pair sequences to encode. + is_pretokenized: Whether inputs are already pre-tokenized. + add_special_tokens: Whether to add special tokens. + + Returns: + A list of Encoding. + """ + if inputs is None: + raise ValueError("async_encode_batch_fast: `inputs` can't be `None`") + return await self._tokenizer.async_encode_batch_fast(inputs, is_pretokenized, add_special_tokens) + + def decode(self, ids: List[int], skip_special_tokens: Optional[bool] = True) -> str: + """Decode the given list of ids to a string sequence + + Args: + ids: List[unsigned int]: + A list of ids to be decoded + + skip_special_tokens: (`optional`) boolean: + Whether to remove all the special tokens from the output string + + Returns: + The decoded string + """ + if ids is None: + raise ValueError("None input is not valid. Should be a list of integers.") + + return self._tokenizer.decode(ids, skip_special_tokens=skip_special_tokens) + + def decode_batch(self, sequences: List[List[int]], skip_special_tokens: Optional[bool] = True) -> str: + """Decode the list of sequences to a list of string sequences + + Args: + sequences: List[List[unsigned int]]: + A list of sequence of ids to be decoded + + skip_special_tokens: (`optional`) boolean: + Whether to remove all the special tokens from the output strings + + Returns: + A list of decoded strings + """ + if sequences is None: + raise ValueError("None input is not valid. Should be list of list of integers.") + + return self._tokenizer.decode_batch(sequences, skip_special_tokens=skip_special_tokens) + + async def async_decode_batch( + self, + sequences: List[List[int]], + skip_special_tokens: bool = True, + ) -> List[str]: + """Asynchronously decode a batch of sequences. + + Args: + sequences: A list of sequences of ids to decode. + skip_special_tokens: Whether to remove special tokens from output. + + Returns: + A list of decoded strings. + """ + if sequences is None: + raise ValueError("async_decode_batch: `sequences` can't be `None`") + return await self._tokenizer.async_decode_batch(sequences, skip_special_tokens) + + def token_to_id(self, token: str) -> Optional[int]: + """Convert the given token to its corresponding id + + Args: + token: str: + The token to convert + + Returns: + The corresponding id if it exists, None otherwise + """ + return self._tokenizer.token_to_id(token) + + def id_to_token(self, id: int) -> Optional[str]: + """Convert the given token id to its corresponding string + + Args: + token: id: + The token id to convert + + Returns: + The corresponding string if it exists, None otherwise + """ + return self._tokenizer.id_to_token(id) + + def save_model(self, directory: str, prefix: Optional[str] = None): + """Save the current model to the given directory + + Args: + directory: str: + A path to the destination directory + + prefix: (Optional) str: + An optional prefix, used to prefix each file name + """ + return self._tokenizer.model.save(directory, prefix=prefix) + + def save(self, path: str, pretty: bool = True): + """Save the current Tokenizer at the given path + + Args: + path: str: + A path to the destination Tokenizer file + """ + return self._tokenizer.save(path, pretty) + + def to_str(self, pretty: bool = False): + """Get a serialized JSON version of the Tokenizer as a str + + Args: + pretty: bool: + Whether the JSON string should be prettified + + Returns: + str + """ + return self._tokenizer.to_str(pretty) + + def post_process( + self, encoding: Encoding, pair: Optional[Encoding] = None, add_special_tokens: bool = True + ) -> Encoding: + """Apply all the post-processing steps to the given encodings. + + The various steps are: + 1. Truncate according to global params (provided to `enable_truncation`) + 2. Apply the PostProcessor + 3. Pad according to global params. (provided to `enable_padding`) + + Args: + encoding: Encoding: + The main Encoding to post process + + pair: Optional[Encoding]: + An optional pair Encoding + + add_special_tokens: bool: + Whether to add special tokens + + Returns: + The resulting Encoding + """ + return self._tokenizer.post_process(encoding, pair, add_special_tokens) + + @property + def model(self) -> Model: + return self._tokenizer.model + + @model.setter + def model(self, model: Model): + self._tokenizer.model = model + + @property + def normalizer(self) -> Normalizer: + return self._tokenizer.normalizer + + @normalizer.setter + def normalizer(self, normalizer: Normalizer): + self._tokenizer.normalizer = normalizer + + @property + def pre_tokenizer(self) -> PreTokenizer: + return self._tokenizer.pre_tokenizer + + @pre_tokenizer.setter + def pre_tokenizer(self, pre_tokenizer: PreTokenizer): + self._tokenizer.pre_tokenizer = pre_tokenizer + + @property + def post_processor(self) -> PostProcessor: + return self._tokenizer.post_processor + + @post_processor.setter + def post_processor(self, post_processor: PostProcessor): + self._tokenizer.post_processor = post_processor + + @property + def decoder(self) -> Decoder: + return self._tokenizer.decoder + + @decoder.setter + def decoder(self, decoder: Decoder): + self._tokenizer.decoder = decoder diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/bert_wordpiece.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/bert_wordpiece.py new file mode 100644 index 0000000000000000000000000000000000000000..ed98c626537d2ad7ec881dc237d91fddaffda9ae --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/bert_wordpiece.py @@ -0,0 +1,151 @@ +from typing import Dict, Iterator, List, Optional, Union + +from tokenizers import AddedToken, Tokenizer, decoders, trainers +from tokenizers.models import WordPiece +from tokenizers.normalizers import BertNormalizer +from tokenizers.pre_tokenizers import BertPreTokenizer +from tokenizers.processors import BertProcessing + +from .base_tokenizer import BaseTokenizer + + +class BertWordPieceTokenizer(BaseTokenizer): + """Bert WordPiece Tokenizer""" + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + unk_token: Union[str, AddedToken] = "[UNK]", + sep_token: Union[str, AddedToken] = "[SEP]", + cls_token: Union[str, AddedToken] = "[CLS]", + pad_token: Union[str, AddedToken] = "[PAD]", + mask_token: Union[str, AddedToken] = "[MASK]", + clean_text: bool = True, + handle_chinese_chars: bool = True, + strip_accents: Optional[bool] = None, + lowercase: bool = True, + wordpieces_prefix: str = "##", + ): + if vocab is not None: + tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(unk_token))) + else: + tokenizer = Tokenizer(WordPiece(unk_token=str(unk_token))) + + # Let the tokenizer know about special tokens if they are part of the vocab + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + if tokenizer.token_to_id(str(sep_token)) is not None: + tokenizer.add_special_tokens([str(sep_token)]) + if tokenizer.token_to_id(str(cls_token)) is not None: + tokenizer.add_special_tokens([str(cls_token)]) + if tokenizer.token_to_id(str(pad_token)) is not None: + tokenizer.add_special_tokens([str(pad_token)]) + if tokenizer.token_to_id(str(mask_token)) is not None: + tokenizer.add_special_tokens([str(mask_token)]) + + tokenizer.normalizer = BertNormalizer( + clean_text=clean_text, + handle_chinese_chars=handle_chinese_chars, + strip_accents=strip_accents, + lowercase=lowercase, + ) + tokenizer.pre_tokenizer = BertPreTokenizer() + + if vocab is not None: + sep_token_id = tokenizer.token_to_id(str(sep_token)) + if sep_token_id is None: + raise TypeError("sep_token not found in the vocabulary") + cls_token_id = tokenizer.token_to_id(str(cls_token)) + if cls_token_id is None: + raise TypeError("cls_token not found in the vocabulary") + + tokenizer.post_processor = BertProcessing((str(sep_token), sep_token_id), (str(cls_token), cls_token_id)) + tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix) + + parameters = { + "model": "BertWordPiece", + "unk_token": unk_token, + "sep_token": sep_token, + "cls_token": cls_token, + "pad_token": pad_token, + "mask_token": mask_token, + "clean_text": clean_text, + "handle_chinese_chars": handle_chinese_chars, + "strip_accents": strip_accents, + "lowercase": lowercase, + "wordpieces_prefix": wordpieces_prefix, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab: str, **kwargs): + vocab = WordPiece.read_file(vocab) + return BertWordPieceTokenizer(vocab, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + special_tokens: List[Union[str, AddedToken]] = [ + "[PAD]", + "[UNK]", + "[CLS]", + "[SEP]", + "[MASK]", + ], + show_progress: bool = True, + wordpieces_prefix: str = "##", + ): + """Train the model using the given files""" + + trainer = trainers.WordPieceTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + special_tokens=special_tokens, + show_progress=show_progress, + continuing_subword_prefix=wordpieces_prefix, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + special_tokens: List[Union[str, AddedToken]] = [ + "[PAD]", + "[UNK]", + "[CLS]", + "[SEP]", + "[MASK]", + ], + show_progress: bool = True, + wordpieces_prefix: str = "##", + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.WordPieceTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + special_tokens=special_tokens, + show_progress=show_progress, + continuing_subword_prefix=wordpieces_prefix, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/byte_level_bpe.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/byte_level_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..f573c15c5a7e4344f712deea45322733819be120 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/byte_level_bpe.py @@ -0,0 +1,122 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, processors, trainers +from tokenizers.models import BPE +from tokenizers.normalizers import Lowercase, Sequence, unicode_normalizer_from_str + +from .base_tokenizer import BaseTokenizer + + +class ByteLevelBPETokenizer(BaseTokenizer): + """ByteLevelBPETokenizer + + Represents a Byte-level BPE as introduced by OpenAI with their GPT-2 model + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + add_prefix_space: bool = False, + lowercase: bool = False, + dropout: Optional[float] = None, + unicode_normalizer: Optional[str] = None, + continuing_subword_prefix: Optional[str] = None, + end_of_word_suffix: Optional[str] = None, + trim_offsets: bool = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer( + BPE( + vocab, + merges, + dropout=dropout, + continuing_subword_prefix=continuing_subword_prefix or "", + end_of_word_suffix=end_of_word_suffix or "", + ) + ) + else: + tokenizer = Tokenizer(BPE()) + + # Check for Unicode normalization first (before everything else) + normalizers = [] + + if unicode_normalizer: + normalizers += [unicode_normalizer_from_str(unicode_normalizer)] + + if lowercase: + normalizers += [Lowercase()] + + # Create the normalizer structure + if len(normalizers) > 0: + if len(normalizers) > 1: + tokenizer.normalizer = Sequence(normalizers) + else: + tokenizer.normalizer = normalizers[0] + + tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space) + tokenizer.decoder = decoders.ByteLevel() + tokenizer.post_processor = processors.ByteLevel(trim_offsets=trim_offsets) + + parameters = { + "model": "ByteLevelBPE", + "add_prefix_space": add_prefix_space, + "lowercase": lowercase, + "dropout": dropout, + "unicode_normalizer": unicode_normalizer, + "continuing_subword_prefix": continuing_subword_prefix, + "end_of_word_suffix": end_of_word_suffix, + "trim_offsets": trim_offsets, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return ByteLevelBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + show_progress: bool = True, + special_tokens: List[Union[str, AddedToken]] = [], + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + show_progress=show_progress, + special_tokens=special_tokens, + initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + show_progress: bool = True, + special_tokens: List[Union[str, AddedToken]] = [], + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + show_progress=show_progress, + special_tokens=special_tokens, + initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/char_level_bpe.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/char_level_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..1891d0435ed429613c1e09486e86165cf19479be --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/char_level_bpe.py @@ -0,0 +1,150 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from .. import AddedToken, Tokenizer, decoders, pre_tokenizers, trainers +from ..models import BPE +from ..normalizers import BertNormalizer, Lowercase, Sequence, unicode_normalizer_from_str +from .base_tokenizer import BaseTokenizer + + +class CharBPETokenizer(BaseTokenizer): + """Original BPE Tokenizer + + Represents the BPE algorithm, as introduced by Rico Sennrich + (https://arxiv.org/abs/1508.07909) + + The defaults settings corresponds to OpenAI GPT BPE tokenizers and differs from the original + Sennrich subword-nmt implementation by the following options that you can deactivate: + - adding a normalizer to clean up the text (deactivate with `bert_normalizer=False`) by: + * removing any control characters and replacing all whitespaces by the classic one. + * handle chinese chars by putting spaces around them. + * strip all accents. + - spitting on punctuation in addition to whitespaces (deactivate it with + `split_on_whitespace_only=True`) + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + unk_token: Union[str, AddedToken] = "", + suffix: str = "", + dropout: Optional[float] = None, + lowercase: bool = False, + unicode_normalizer: Optional[str] = None, + bert_normalizer: bool = True, + split_on_whitespace_only: bool = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer( + BPE( + vocab, + merges, + dropout=dropout, + unk_token=str(unk_token), + end_of_word_suffix=suffix, + ) + ) + else: + tokenizer = Tokenizer(BPE(unk_token=str(unk_token), dropout=dropout, end_of_word_suffix=suffix)) + + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + + # Check for Unicode normalization first (before everything else) + normalizers = [] + + if unicode_normalizer: + normalizers += [unicode_normalizer_from_str(unicode_normalizer)] + + if bert_normalizer: + normalizers += [BertNormalizer(lowercase=False)] + + if lowercase: + normalizers += [Lowercase()] + + # Create the normalizer structure + if len(normalizers) > 0: + if len(normalizers) > 1: + tokenizer.normalizer = Sequence(normalizers) + else: + tokenizer.normalizer = normalizers[0] + + if split_on_whitespace_only: + tokenizer.pre_tokenizer = pre_tokenizers.WhitespaceSplit() + else: + tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() + + tokenizer.decoder = decoders.BPEDecoder(suffix=suffix) + + parameters = { + "model": "BPE", + "unk_token": unk_token, + "suffix": suffix, + "dropout": dropout, + "lowercase": lowercase, + "unicode_normalizer": unicode_normalizer, + "bert_normalizer": bert_normalizer, + "split_on_whitespace_only": split_on_whitespace_only, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return CharBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + suffix: Optional[str] = "", + show_progress: bool = True, + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + end_of_word_suffix=suffix, + show_progress=show_progress, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + suffix: Optional[str] = "", + show_progress: bool = True, + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + end_of_word_suffix=suffix, + show_progress=show_progress, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_bpe.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_bpe.py new file mode 100644 index 0000000000000000000000000000000000000000..912fa4676930004ebc0a620b5bc7c1cfb61c3be7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_bpe.py @@ -0,0 +1,103 @@ +from typing import Dict, Iterator, List, Optional, Tuple, Union + +from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, trainers +from tokenizers.models import BPE +from tokenizers.normalizers import NFKC + +from .base_tokenizer import BaseTokenizer + + +class SentencePieceBPETokenizer(BaseTokenizer): + """SentencePiece BPE Tokenizer + + Represents the BPE algorithm, with the pretokenization used by SentencePiece + """ + + def __init__( + self, + vocab: Optional[Union[str, Dict[str, int]]] = None, + merges: Optional[Union[str, List[Tuple[str, str]]]] = None, + unk_token: Union[str, AddedToken] = "", + replacement: str = "▁", + add_prefix_space: bool = True, + dropout: Optional[float] = None, + fuse_unk: Optional[bool] = False, + ): + if vocab is not None and merges is not None: + tokenizer = Tokenizer(BPE(vocab, merges, dropout=dropout, unk_token=unk_token, fuse_unk=fuse_unk)) + else: + tokenizer = Tokenizer(BPE(dropout=dropout, unk_token=unk_token, fuse_unk=fuse_unk)) + + if tokenizer.token_to_id(str(unk_token)) is not None: + tokenizer.add_special_tokens([str(unk_token)]) + + tokenizer.normalizer = NFKC() + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceBPE", + "unk_token": unk_token, + "replacement": replacement, + "add_prefix_space": add_prefix_space, + "dropout": dropout, + } + + super().__init__(tokenizer, parameters) + + @staticmethod + def from_file(vocab_filename: str, merges_filename: str, **kwargs): + vocab, merges = BPE.read_file(vocab_filename, merges_filename) + return SentencePieceBPETokenizer(vocab, merges, **kwargs) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + show_progress: bool = True, + ): + """Train the model using the given files""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + show_progress=show_progress, + ) + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 30000, + min_frequency: int = 2, + special_tokens: List[Union[str, AddedToken]] = [""], + limit_alphabet: int = 1000, + initial_alphabet: List[str] = [], + show_progress: bool = True, + length: Optional[int] = None, + ): + """Train the model using the given iterator""" + + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + min_frequency=min_frequency, + special_tokens=special_tokens, + limit_alphabet=limit_alphabet, + initial_alphabet=initial_alphabet, + show_progress=show_progress, + ) + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) diff --git a/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_unigram.py b/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_unigram.py new file mode 100644 index 0000000000000000000000000000000000000000..26ce12e7d1eee6202668f125f255d7c5fe470c8a --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/implementations/sentencepiece_unigram.py @@ -0,0 +1,196 @@ +import json +import os +from typing import Iterator, List, Optional, Union, Tuple + +from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers +from tokenizers.models import Unigram + +from .base_tokenizer import BaseTokenizer + + +class SentencePieceUnigramTokenizer(BaseTokenizer): + """SentencePiece Unigram Tokenizer + + Represents the Unigram algorithm, with the pretokenization used by SentencePiece + """ + + def __init__( + self, + vocab: Optional[List[Tuple[str, float]]] = None, + replacement: str = "▁", + add_prefix_space: bool = True, + ): + if vocab is not None: + # Let Unigram(..) fail if only one of them is None + tokenizer = Tokenizer(Unigram(vocab)) + else: + tokenizer = Tokenizer(Unigram()) + + tokenizer.normalizer = normalizers.Sequence( + [normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(" {2,}"), " ")] + ) + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceUnigram", + "replacement": replacement, + "add_prefix_space": add_prefix_space, + } + + super().__init__(tokenizer, parameters) + + def train( + self, + files: Union[str, List[str]], + vocab_size: int = 8000, + show_progress: bool = True, + special_tokens: Optional[List[Union[str, AddedToken]]] = None, + initial_alphabet: Optional[List[str]] = None, + unk_token: Optional[str] = None, + ): + """ + Train the model using the given files + + Args: + files (:obj:`List[str]`): + A list of path to the files that we should use for training + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + show_progress (:obj:`bool`): + Whether to show progress bars while training. + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + """ + + if special_tokens is None: + special_tokens = [] + + if initial_alphabet is None: + initial_alphabet = [] + + trainer = trainers.UnigramTrainer( + vocab_size=vocab_size, + special_tokens=special_tokens, + show_progress=show_progress, + initial_alphabet=initial_alphabet, + unk_token=unk_token, + ) + + if isinstance(files, str): + files = [files] + self._tokenizer.train(files, trainer=trainer) + + def train_from_iterator( + self, + iterator: Union[Iterator[str], Iterator[Iterator[str]]], + vocab_size: int = 8000, + show_progress: bool = True, + special_tokens: Optional[List[Union[str, AddedToken]]] = None, + initial_alphabet: Optional[List[str]] = None, + unk_token: Optional[str] = None, + length: Optional[int] = None, + ): + """ + Train the model using the given iterator + + Args: + iterator (:obj:`Union[Iterator[str], Iterator[Iterator[str]]]`): + Any iterator over strings or list of strings + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + show_progress (:obj:`bool`): + Whether to show progress bars while training. + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + unk_token (:obj:`str`, `optional`): + The unknown token to be used by the model. + length (:obj:`int`, `optional`): + The total number of sequences in the iterator. This is used to + provide meaningful progress tracking + """ + + if special_tokens is None: + special_tokens = [] + + if initial_alphabet is None: + initial_alphabet = [] + + trainer = trainers.UnigramTrainer( + vocab_size=vocab_size, + special_tokens=special_tokens, + show_progress=show_progress, + initial_alphabet=initial_alphabet, + unk_token=unk_token, + ) + + self._tokenizer.train_from_iterator( + iterator, + trainer=trainer, + length=length, + ) + + @staticmethod + def from_spm(filename: str): + try: + import sys + + sys.path.append(".") + + import sentencepiece_model_pb2 as model # type: ignore[import] + except Exception: + raise Exception( + "You don't seem to have the required protobuf file, in order to use this function you need to run `pip install protobuf` and `wget https://raw.githubusercontent.com/google/sentencepiece/master/python/src/sentencepiece/sentencepiece_model_pb2.py` for us to be able to read the intrinsics of your spm_file. `pip install sentencepiece` is not required." + ) + + m = model.ModelProto() + m.ParseFromString(open(filename, "rb").read()) + + precompiled_charsmap = m.normalizer_spec.precompiled_charsmap + vocab = [(piece.piece, piece.score) for piece in m.pieces] + unk_id = m.trainer_spec.unk_id + model_type = m.trainer_spec.model_type + byte_fallback = m.trainer_spec.byte_fallback + if model_type != 1: + raise Exception( + "You're trying to run a `Unigram` model but you're file was trained with a different algorithm" + ) + + replacement = "▁" + add_prefix_space = True + + tokenizer = Tokenizer(Unigram(vocab, unk_id, byte_fallback)) + + if precompiled_charsmap: + tokenizer.normalizer = normalizers.Sequence( + [ + normalizers.Precompiled(precompiled_charsmap), + normalizers.Replace(Regex(" {2,}"), " "), + ] + ) + else: + tokenizer.normalizer = normalizers.Sequence([normalizers.Replace(Regex(" {2,}"), " ")]) + prepend_scheme = "always" if add_prefix_space else "never" + tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + tokenizer.decoder = decoders.Metaspace(replacement=replacement, prepend_scheme=prepend_scheme) + + parameters = { + "model": "SentencePieceUnigram", + } + + obj = BaseTokenizer.__new__(SentencePieceUnigramTokenizer, tokenizer, parameters) # type: ignore[arg-type] + BaseTokenizer.__init__(obj, tokenizer, parameters) + return obj diff --git a/python/user_packages/Python313/site-packages/tokenizers/models/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3879df748ecfacca1ee43839e33a2aff962b11c --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/models/__init__.py @@ -0,0 +1,9 @@ +# Generated content DO NOT EDIT + +from .. import models + +BPE = models.BPE +Model = models.Model +Unigram = models.Unigram +WordLevel = models.WordLevel +WordPiece = models.WordPiece diff --git a/python/user_packages/Python313/site-packages/tokenizers/models/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/models/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32107d708265b6c62eb4ae9766896138019ae77 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/models/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/normalizers/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/normalizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7b7476ef32ee94036ad57c7f88956552018ca7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/normalizers/__init__.py @@ -0,0 +1,29 @@ +from .. import normalizers + + +Normalizer = normalizers.Normalizer +BertNormalizer = normalizers.BertNormalizer +NFD = normalizers.NFD +NFKD = normalizers.NFKD +NFC = normalizers.NFC +NFKC = normalizers.NFKC +Sequence = normalizers.Sequence +Lowercase = normalizers.Lowercase +Prepend = normalizers.Prepend +Strip = normalizers.Strip +StripAccents = normalizers.StripAccents +Nmt = normalizers.Nmt +Precompiled = normalizers.Precompiled +Replace = normalizers.Replace +ByteLevel = normalizers.ByteLevel + +NORMALIZERS = {"nfc": NFC, "nfd": NFD, "nfkc": NFKC, "nfkd": NFKD} + + +def unicode_normalizer_from_str(normalizer: str) -> Normalizer: + if normalizer not in NORMALIZERS: + raise ValueError( + "{} is not a known unicode normalizer. Available are {}".format(normalizer, NORMALIZERS.keys()) + ) + + return NORMALIZERS[normalizer]() diff --git a/python/user_packages/Python313/site-packages/tokenizers/normalizers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/normalizers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..836cf8f771433a3411c1c28d3a86e4627af31306 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/normalizers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1971cbbf170f65b5ac1cac04786c163e38bc0805 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__init__.py @@ -0,0 +1,17 @@ +# Generated content DO NOT EDIT + +from .. import pre_tokenizers + +BertPreTokenizer = pre_tokenizers.BertPreTokenizer +ByteLevel = pre_tokenizers.ByteLevel +CharDelimiterSplit = pre_tokenizers.CharDelimiterSplit +Digits = pre_tokenizers.Digits +FixedLength = pre_tokenizers.FixedLength +Metaspace = pre_tokenizers.Metaspace +PreTokenizer = pre_tokenizers.PreTokenizer +Punctuation = pre_tokenizers.Punctuation +Sequence = pre_tokenizers.Sequence +Split = pre_tokenizers.Split +UnicodeScripts = pre_tokenizers.UnicodeScripts +Whitespace = pre_tokenizers.Whitespace +WhitespaceSplit = pre_tokenizers.WhitespaceSplit diff --git a/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af55960a592a6a7d2eb40e61ce2fda7ca3bd8ef7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/pre_tokenizers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/processors/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/processors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d790baffc1b3762446454230bec231fabe6abd8b --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/processors/__init__.py @@ -0,0 +1,10 @@ +# Generated content DO NOT EDIT + +from .. import processors + +BertProcessing = processors.BertProcessing +ByteLevel = processors.ByteLevel +PostProcessor = processors.PostProcessor +RobertaProcessing = processors.RobertaProcessing +Sequence = processors.Sequence +TemplateProcessing = processors.TemplateProcessing diff --git a/python/user_packages/Python313/site-packages/tokenizers/processors/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/processors/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9725f1e2ab98372372bacb58b897edae8f89137 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/processors/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/tools/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d166cb9015bd967669e50341c3966297c447735 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/tools/__init__.py @@ -0,0 +1 @@ +from .visualizer import Annotation, EncodingVisualizer diff --git a/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c198dba9116553cfa328541b7653c0ca2836f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/visualizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/visualizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..302f5b9c67d7c166c27e2e70357f0184b2ee2db5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/tools/__pycache__/visualizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer-styles.css b/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer-styles.css new file mode 100644 index 0000000000000000000000000000000000000000..c108d667b391694d94c15fd583b2491e438ec058 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer-styles.css @@ -0,0 +1,170 @@ +.tokenized-text { + width:100%; + padding:2rem; + max-height: 400px; + overflow-y: auto; + box-sizing:border-box; + line-height:4rem; /* Lots of space between lines */ + font-family: "Roboto Light", "Ubuntu Light", "Ubuntu", monospace; + box-shadow: 2px 2px 2px rgba(0,0,0,0.2); + background-color: rgba(0,0,0,0.01); + letter-spacing:2px; /* Give some extra separation between chars */ +} +.non-token{ + /* White space and other things the tokenizer ignores*/ + white-space: pre; + letter-spacing:4px; + border-top:1px solid #A0A0A0; /* A gentle border on top and bottom makes tabs more ovious*/ + border-bottom:1px solid #A0A0A0; + line-height: 1rem; + height: calc(100% - 2px); +} + +.token { + white-space: pre; + position:relative; + color:black; + letter-spacing:2px; +} + +.annotation{ + white-space:nowrap; /* Important - ensures that annotations appears even if the annotated text wraps a line */ + border-radius:4px; + position:relative; + width:fit-content; +} +.annotation:before { + /*The before holds the text and the after holds the background*/ + z-index:1000; /* Make sure this is above the background */ + content:attr(data-label); /* The annotations label is on a data attribute */ + color:white; + position:absolute; + font-size:1rem; + text-align:center; + font-weight:bold; + + top:1.75rem; + line-height:0; + left:0; + width:100%; + padding:0.5rem 0; + /* These make it so an annotation doesn't stretch beyond the annotated text if the label is longer*/ + overflow: hidden; + white-space: nowrap; + text-overflow:ellipsis; +} + +.annotation:after { + content:attr(data-label); /* The content defines the width of the annotation*/ + position:absolute; + font-size:0.75rem; + text-align:center; + font-weight:bold; + text-overflow:ellipsis; + top:1.75rem; + line-height:0; + overflow: hidden; + white-space: nowrap; + + left:0; + width:100%; /* 100% of the parent, which is the annotation whose width is the tokens inside it*/ + + padding:0.5rem 0; + /* Nast hack below: + We set the annotations color in code because we don't know the colors at css time. + But you can't pass a color as a data attribute to get it into the pseudo element (this thing) + So to get around that, annotations have the color set on them with a style attribute and then we + can get the color with currentColor. + Annotations wrap tokens and tokens set the color back to black + */ + background-color: currentColor; +} +.annotation:hover::after, .annotation:hover::before{ + /* When the user hovers over an annotation expand the label to display in full + */ + min-width: fit-content; +} + +.annotation:hover{ + /* Emphasize the annotation start end with a border on hover*/ + border-color: currentColor; + border: 2px solid; +} +.special-token:not(:empty){ + /* + A none empty special token is like UNK (as opposed to CLS which has no representation in the text ) + */ + position:relative; +} +.special-token:empty::before{ + /* Special tokens that don't have text are displayed as pseudo elements so we dont select them with the mouse*/ + content:attr(data-stok); + background:#202020; + font-size:0.75rem; + color:white; + margin: 0 0.25rem; + padding: 0.25rem; + border-radius:4px +} + +.special-token:not(:empty):before { + /* Special tokens that have text (UNK) are displayed above the actual text*/ + content:attr(data-stok); + position:absolute; + bottom:1.75rem; + min-width:100%; + width:100%; + height:1rem; + line-height:1rem; + font-size:1rem; + text-align:center; + color:white; + font-weight:bold; + background:#202020; + border-radius:10%; +} +/* +We want to alternate the color of tokens, but we can't use nth child because tokens might be broken up by annotations +instead we apply even and odd class at generation time and color them that way + */ +.even-token{ + background:#DCDCDC ; + border: 1px solid #DCDCDC; +} +.odd-token{ + background:#A0A0A0; + border: 1px solid #A0A0A0; +} +.even-token.multi-token,.odd-token.multi-token{ + background: repeating-linear-gradient( + 45deg, + transparent, + transparent 1px, + #ccc 1px, + #ccc 1px + ), + /* on "bottom" */ + linear-gradient( + to bottom, + #FFB6C1, + #999 + ); +} + +.multi-token:hover::after { + content:"This char has more than 1 token"; /* The content defines the width of the annotation*/ + color:white; + background-color: black; + position:absolute; + font-size:0.75rem; + text-align:center; + font-weight:bold; + text-overflow:ellipsis; + top:1.75rem; + line-height:0; + overflow: hidden; + white-space: nowrap; + left:0; + width:fit-content; /* 100% of the parent, which is the annotation whose width is the tokens inside it*/ + padding:0.5rem 0; +} diff --git a/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer.py b/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7a436d8ac457483de3059c1e12e89810d17aa4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/tools/visualizer.py @@ -0,0 +1,420 @@ +import html +import itertools +import os +import re +from string import Template +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple + +from tokenizers import Encoding, Tokenizer + +dirname = os.path.dirname(__file__) +css_filename = os.path.join(dirname, "visualizer-styles.css") +with open(css_filename) as f: + css = f.read() + + +class Annotation: + start: int + end: int + label: str + + def __init__(self, start: int, end: int, label: str): + self.start = start + self.end = end + self.label = label + + +AnnotationList = List[Annotation] +PartialIntList = List[Optional[int]] + + +class CharStateKey(NamedTuple): + token_ix: Optional[int] + anno_ix: Optional[int] + + +class CharState: + char_ix: Optional[int] + + def __init__(self, char_ix): + self.char_ix = char_ix + + self.anno_ix: Optional[int] = None + self.tokens: List[int] = [] + + @property + def token_ix(self): + return self.tokens[0] if len(self.tokens) > 0 else None + + @property + def is_multitoken(self): + """ + BPE tokenizers can output more than one token for a char + """ + return len(self.tokens) > 1 + + def partition_key(self) -> CharStateKey: + return CharStateKey( + token_ix=self.token_ix, + anno_ix=self.anno_ix, + ) + + +class Aligned: + pass + + +class EncodingVisualizer: + """ + Build an EncodingVisualizer + + Args: + + tokenizer (:class:`~tokenizers.Tokenizer`): + A tokenizer instance + + default_to_notebook (:obj:`bool`): + Whether to render html output in a notebook by default + + annotation_converter (:obj:`Callable`, `optional`): + An optional (lambda) function that takes an annotation in any format and returns + an Annotation object + """ + + unk_token_regex = re.compile("(.{1}\b)?(unk|oov)(\b.{1})?", flags=re.IGNORECASE) + + def __init__( + self, + tokenizer: Tokenizer, + default_to_notebook: bool = True, + annotation_converter: Optional[Callable[[Any], Annotation]] = None, + ): + if default_to_notebook: + try: + from IPython.display import HTML, display # type: ignore[attr-defined] + except ImportError: + try: + from IPython.core.display import HTML, display # type: ignore[attr-defined] + except ImportError: + msg = ( + "We couldn't import IPython utils for html display.\n" + "Are you running in a notebook?\n" + "You can also pass `default_to_notebook=False` to get back raw HTML.\n" + ) + raise ImportError(msg) from None + self.tokenizer = tokenizer + self.default_to_notebook = default_to_notebook + self.annotation_coverter = annotation_converter + pass + + def __call__( + self, + text: str, + annotations: Optional[List[Any]] = None, + default_to_notebook: Optional[bool] = None, + ) -> Optional[str]: + """ + Build a visualization of the given text + + Args: + text (:obj:`str`): + The text to tokenize + + annotations (:obj:`List[Annotation]`, `optional`): + An optional list of annotations of the text. The can either be an annotation class + or anything else if you instantiated the visualizer with a converter function + + default_to_notebook (:obj:`bool`, `optional`, defaults to `False`): + If True, will render the html in a notebook. Otherwise returns an html string. + + Returns: + The HTML string if default_to_notebook is False, otherwise (default) returns None and + renders the HTML in the notebook + + """ + final_default_to_notebook = self.default_to_notebook + if default_to_notebook is not None: + final_default_to_notebook = default_to_notebook + if final_default_to_notebook: + try: + from IPython.display import HTML, display # type: ignore[attr-defined] + except ImportError: + try: + from IPython.core.display import HTML, display # type: ignore[attr-defined] + except ImportError: + msg = ( + "We couldn't import IPython utils for html display.\n" + "Are you running in a notebook?\n" + "You can also pass `default_to_notebook=False` to get back raw HTML.\n" + ) + raise ImportError(msg) from None + if annotations is None: + annotations = [] + if self.annotation_coverter is not None: + annotations = list(map(self.annotation_coverter, annotations)) + encoding = self.tokenizer.encode(text) + html = EncodingVisualizer.__make_html(text, encoding, annotations) + if final_default_to_notebook: + display(HTML(html)) + else: + return html + + @staticmethod + def calculate_label_colors(annotations: AnnotationList) -> Dict[str, str]: + """ + Generates a color palette for all the labels in a given set of annotations + + Args: + annotations (:obj:`Annotation`): + A list of annotations + + Returns: + :obj:`dict`: A dictionary mapping labels to colors in HSL format + """ + if len(annotations) == 0: + return {} + labels = set(map(lambda x: x.label, annotations)) + num_labels = len(labels) + h_step = int(255 / num_labels) + if h_step < 20: + h_step = 20 + s = 32 + l = 64 # noqa: E741 + h = 10 + colors = {} + + for label in sorted(labels): # sort so we always get the same colors for a given set of labels + colors[label] = f"hsl({h},{s}%,{l}%)" + h += h_step + return colors + + @staticmethod + def consecutive_chars_to_html( + consecutive_chars_list: List[CharState], + text: str, + encoding: Encoding, + ): + """ + Converts a list of "consecutive chars" into a single HTML element. + Chars are consecutive if they fall under the same word, token and annotation. + The CharState class is a named tuple with a "partition_key" method that makes it easy to + compare if two chars are consecutive. + + Args: + consecutive_chars_list (:obj:`List[CharState]`): + A list of CharStates that have been grouped together + + text (:obj:`str`): + The original text being processed + + encoding (:class:`~tokenizers.Encoding`): + The encoding returned from the tokenizer + + Returns: + :obj:`str`: The HTML span for a set of consecutive chars + """ + first = consecutive_chars_list[0] + if first.char_ix is None: + # its a special token + stoken = encoding.tokens[first.token_ix] + # special tokens are represented as empty spans. We use the data attribute and css + # magic to display it + return f'' + # We're not in a special token so this group has a start and end. + last = consecutive_chars_list[-1] + assert first.char_ix is not None + assert last.char_ix is not None + start = first.char_ix + end = last.char_ix + 1 + span_text = text[start:end] + css_classes = [] # What css classes will we apply on the resulting span + data_items = {} # What data attributes will we apply on the result span + if first.token_ix is not None: + # We can either be in a token or not (e.g. in white space) + css_classes.append("token") + if first.is_multitoken: + css_classes.append("multi-token") + if first.token_ix % 2: + # We use this to color alternating tokens. + # A token might be split by an annotation that ends in the middle of it, so this + # lets us visually indicate a consecutive token despite its possible splitting in + # the html markup + css_classes.append("odd-token") + else: + # Like above, but a different color so we can see the tokens alternate + css_classes.append("even-token") + if EncodingVisualizer.unk_token_regex.search(encoding.tokens[first.token_ix]) is not None: + # This is a special token that is in the text. probably UNK + css_classes.append("special-token") + # TODO is this the right name for the data attribute ? + data_items["stok"] = encoding.tokens[first.token_ix] + else: + # In this case we are looking at a group/single char that is not tokenized. + # e.g. white space + css_classes.append("non-token") + css = f'''class="{" ".join(css_classes)}"''' + data = "" + for key, val in data_items.items(): + data += f' data-{key}="{val}"' + span_text = html.escape(span_text) + return f"{span_text}" + + @staticmethod + def __make_html(text: str, encoding: Encoding, annotations: AnnotationList) -> str: + char_states = EncodingVisualizer.__make_char_states(text, encoding, annotations) + current_consecutive_chars = [char_states[0]] + prev_anno_ix = char_states[0].anno_ix + spans = [] + label_colors_dict = EncodingVisualizer.calculate_label_colors(annotations) + cur_anno_ix = char_states[0].anno_ix + if cur_anno_ix is not None: + # If we started in an annotation make a span for it + anno = annotations[cur_anno_ix] + label = anno.label + color = label_colors_dict[label] + spans.append(f'') + + for cs in char_states[1:]: + cur_anno_ix = cs.anno_ix + if cur_anno_ix != prev_anno_ix: + # If we've transitioned in or out of an annotation + spans.append( + # Create a span from the current consecutive characters + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + current_consecutive_chars = [cs] + + if prev_anno_ix is not None: + # if we transitioned out of an annotation close it's span + spans.append("") + if cur_anno_ix is not None: + # If we entered a new annotation make a span for it + anno = annotations[cur_anno_ix] + label = anno.label + color = label_colors_dict[label] + spans.append(f'') + prev_anno_ix = cur_anno_ix + + if cs.partition_key() == current_consecutive_chars[0].partition_key(): + # If the current charchter is in the same "group" as the previous one + current_consecutive_chars.append(cs) + else: + # Otherwise we make a span for the previous group + spans.append( + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + # An reset the consecutive_char_list to form a new group + current_consecutive_chars = [cs] + # All that's left is to fill out the final span + # TODO I think there is an edge case here where an annotation's span might not close + spans.append( + EncodingVisualizer.consecutive_chars_to_html( + current_consecutive_chars, + text=text, + encoding=encoding, + ) + ) + + # Close any remaining open annotation span + if cur_anno_ix is not None: + spans.append("") + + res = HTMLBody(spans) # Send the list of spans to the body of our html + return res + + @staticmethod + def __make_anno_map(text: str, annotations: AnnotationList) -> PartialIntList: + """ + Args: + text (:obj:`str`): + The raw text we want to align to + + annotations (:obj:`AnnotationList`): + A (possibly empty) list of annotations + + Returns: + A list of length len(text) whose entry at index i is None if there is no annotation on + character i or k, the index of the annotation that covers index i where k is with + respect to the list of annotations + """ + annotation_map = [None] * len(text) + for anno_ix, a in enumerate(annotations): + for i in range(a.start, a.end): + annotation_map[i] = anno_ix + return annotation_map + + @staticmethod + def __make_char_states(text: str, encoding: Encoding, annotations: AnnotationList) -> List[CharState]: + """ + For each character in the original text, we emit a tuple representing it's "state": + + * which token_ix it corresponds to + * which word_ix it corresponds to + * which annotation_ix it corresponds to + + Args: + text (:obj:`str`): + The raw text we want to align to + + annotations (:obj:`List[Annotation]`): + A (possibly empty) list of annotations + + encoding: (:class:`~tokenizers.Encoding`): + The encoding returned from the tokenizer + + Returns: + :obj:`List[CharState]`: A list of CharStates, indicating for each char in the text what + it's state is + """ + annotation_map = EncodingVisualizer.__make_anno_map(text, annotations) + # Todo make this a dataclass or named tuple + char_states: List[CharState] = [CharState(char_ix) for char_ix in range(len(text))] + for token_ix, token in enumerate(encoding.tokens): + offsets = encoding.token_to_chars(token_ix) + if offsets is not None: + start, end = offsets + for i in range(start, end): + char_states[i].tokens.append(token_ix) + for char_ix, anno_ix in enumerate(annotation_map): + char_states[char_ix].anno_ix = anno_ix + + return char_states + + +def HTMLBody(children: List[str], css_styles=css) -> str: + """ + Generates the full html with css from a list of html spans + + Args: + children (:obj:`List[str]`): + A list of strings, assumed to be html elements + + css_styles (:obj:`str`, `optional`): + Optional alternative implementation of the css + + Returns: + :obj:`str`: An HTML string with style markup + """ + children_text = "".join(children) + return f""" + + + + + +
+ {children_text} +
+ + + """ diff --git a/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.py b/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd301d8afedf1465e40d723bb67522ebc4111c11 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.py @@ -0,0 +1,9 @@ +# Generated content DO NOT EDIT + +from .. import trainers + +BpeTrainer = trainers.BpeTrainer +Trainer = trainers.Trainer +UnigramTrainer = trainers.UnigramTrainer +WordLevelTrainer = trainers.WordLevelTrainer +WordPieceTrainer = trainers.WordPieceTrainer diff --git a/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.pyi b/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f296988dcaf70cbe6fe5e2d9b99b12d80b8394b1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tokenizers/trainers/__init__.pyi @@ -0,0 +1,462 @@ +# Generated content DO NOT EDIT +class Trainer: + """ + Base class for all trainers + + This class is not supposed to be instantiated directly. Instead, any implementation of a + Trainer will return an instance of this class when instantiated. + """ + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + +class BpeTrainer(Trainer): + """ + Trainer capable of training a BPE model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + + limit_alphabet (:obj:`int`, `optional`): + The maximum different characters to keep in the alphabet. + + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + continuing_subword_prefix (:obj:`str`, `optional`): + A prefix to be used for every subword that is not a beginning-of-word. + + end_of_word_suffix (:obj:`str`, `optional`): + A suffix to be used for every subword that is a end-of-word. + + max_token_length (:obj:`int`, `optional`): + Prevents creating tokens longer than the specified size. + This can help with reducing polluting your vocabulary with + highly repetitive tokens like `======` for wikipedia + + """ + def __init__( + self, + vocab_size=30000, + min_frequency=0, + show_progress=True, + special_tokens=[], + limit_alphabet=None, + initial_alphabet=[], + continuing_subword_prefix=None, + end_of_word_suffix=None, + max_token_length=None, + words={}, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @property + def end_of_word_suffix(self): + """ """ + pass + + @end_of_word_suffix.setter + def end_of_word_suffix(self, value): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def limit_alphabet(self): + """ """ + pass + + @limit_alphabet.setter + def limit_alphabet(self, value): + """ """ + pass + + @property + def max_token_length(self): + """ """ + pass + + @max_token_length.setter + def max_token_length(self, value): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class UnigramTrainer(Trainer): + """ + Trainer capable of training a Unigram model + + Args: + vocab_size (:obj:`int`): + The size of the final vocabulary, including all tokens and alphabet. + + show_progress (:obj:`bool`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`): + A list of special tokens the model should know of. + + initial_alphabet (:obj:`List[str]`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + shrinking_factor (:obj:`float`): + The shrinking factor used at each step of the training to prune the + vocabulary. + + unk_token (:obj:`str`): + The token used for out-of-vocabulary tokens. + + max_piece_length (:obj:`int`): + The maximum length of a given token. + + n_sub_iterations (:obj:`int`): + The number of iterations of the EM algorithm to perform before + pruning the vocabulary. + """ + def __init__( + self, + vocab_size=8000, + show_progress=True, + special_tokens=[], + initial_alphabet=[], + shrinking_factor=0.75, + unk_token=None, + max_piece_length=16, + n_sub_iterations=2, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class WordLevelTrainer(Trainer): + """ + Trainer capable of training a WorldLevel model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`): + A list of special tokens the model should know of. + """ + def __init__(self, vocab_size=30000, min_frequency=0, show_progress=True, special_tokens=[]): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass + +class WordPieceTrainer(Trainer): + """ + Trainer capable of training a WordPiece model + + Args: + vocab_size (:obj:`int`, `optional`): + The size of the final vocabulary, including all tokens and alphabet. + + min_frequency (:obj:`int`, `optional`): + The minimum frequency a pair should have in order to be merged. + + show_progress (:obj:`bool`, `optional`): + Whether to show progress bars while training. + + special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`): + A list of special tokens the model should know of. + + limit_alphabet (:obj:`int`, `optional`): + The maximum different characters to keep in the alphabet. + + initial_alphabet (:obj:`List[str]`, `optional`): + A list of characters to include in the initial alphabet, even + if not seen in the training dataset. + If the strings contain more than one character, only the first one + is kept. + + continuing_subword_prefix (:obj:`str`, `optional`): + A prefix to be used for every subword that is not a beginning-of-word. + + end_of_word_suffix (:obj:`str`, `optional`): + A suffix to be used for every subword that is a end-of-word. + """ + def __init__( + self, + vocab_size=30000, + min_frequency=0, + show_progress=True, + special_tokens=[], + limit_alphabet=None, + initial_alphabet=[], + continuing_subword_prefix="##", + end_of_word_suffix=None, + ): + pass + + def __getstate__(self): + """ """ + pass + + def __setstate__(self, state): + """ """ + pass + + @property + def continuing_subword_prefix(self): + """ """ + pass + + @continuing_subword_prefix.setter + def continuing_subword_prefix(self, value): + """ """ + pass + + @property + def end_of_word_suffix(self): + """ """ + pass + + @end_of_word_suffix.setter + def end_of_word_suffix(self, value): + """ """ + pass + + @property + def initial_alphabet(self): + """ """ + pass + + @initial_alphabet.setter + def initial_alphabet(self, value): + """ """ + pass + + @property + def limit_alphabet(self): + """ """ + pass + + @limit_alphabet.setter + def limit_alphabet(self, value): + """ """ + pass + + @property + def min_frequency(self): + """ """ + pass + + @min_frequency.setter + def min_frequency(self, value): + """ """ + pass + + @property + def show_progress(self): + """ """ + pass + + @show_progress.setter + def show_progress(self, value): + """ """ + pass + + @property + def special_tokens(self): + """ """ + pass + + @special_tokens.setter + def special_tokens(self, value): + """ """ + pass + + @property + def vocab_size(self): + """ """ + pass + + @vocab_size.setter + def vocab_size(self, value): + """ """ + pass diff --git a/python/user_packages/Python313/site-packages/tokenizers/trainers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tokenizers/trainers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e289e8c1d82717c275559c42df2daf60002d0968 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tokenizers/trainers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado-6.5.5.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/tornado-6.5.5.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..75b52484ea471f882c29e02693b4f02dba175b5e --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado-6.5.5.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6c6a6847fa03c22359ff4db5c7bb6ee2cfd9698 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/_locale_data.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/_locale_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d74f2f85e9ef4b87d293f1ad4d5988279221e1c2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/_locale_data.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/auth.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e565c8948d026918b077ef4f1b21483ac76e1f4b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/auth.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/autoreload.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/autoreload.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9949e68761e3ee9916f0766dcf6b6267ec62050c Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/autoreload.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/concurrent.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/concurrent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b62f438539980e146c826dd74671aa40225a2e03 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/concurrent.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/curl_httpclient.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/curl_httpclient.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fae6da0e99f61a6f57d6718ced237fb00a75dde Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/curl_httpclient.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/escape.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/escape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09eb6f53c116d611ca608b670bc18090874d28d Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/escape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/gen.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/gen.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aded62445a04ba049e46bbfc642dfc151205c10 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/gen.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/http1connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/http1connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f67b7807e58344023628072ef70dd885b442f818 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/http1connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/httpclient.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/httpclient.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c816c350daa4d333e521a5fb63ad1727fa467b9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/httpclient.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/httpserver.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/httpserver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b64b8db9fa2311e83d0b157a2147f26a0167d361 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/httpserver.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/httputil.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/httputil.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49e2ec2f660ac0c60b227006cdca17fdca7fe326 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/httputil.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/ioloop.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/ioloop.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4b08cce2bae01b39ed77a38906e467971ee630b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/ioloop.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/iostream.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/iostream.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bac17134cfaf6cd7ae47b023807136315c1debf8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/iostream.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/locale.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/locale.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96bfd82344c9656196abce86efaa21b75107c3bc Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/locale.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/locks.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/locks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97a627013bf60840232b328f0c8c6043d3c329c6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/locks.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/log.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/log.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1fa032d56a0c9efe1d28328fde1bb8e4cee7f31 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/log.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/netutil.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/netutil.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ce5a2ce95bd95e536c8edbb14e72d53774dd89 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/netutil.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/options.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/options.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdc92ff94e0b173b58ba153cdcdd21dea0da50b0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/options.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/process.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/process.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10bea7fc21d83396c6d1b5a084fa76baf91c890 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/process.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/queues.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/queues.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96b038574bb390677c2cf068bece5cd75d664dab Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/queues.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/routing.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/routing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a88561afdb3d2ffb9553f228c3a106b484b83cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/routing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/simple_httpclient.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/simple_httpclient.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6aa87247429c79116c24c013ab1ec00a902194 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/simple_httpclient.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpclient.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpclient.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..807a75950b0ef9a447438a40b37fd733513fa843 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpclient.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpserver.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpserver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c851f6502782dc11f0dc702d344d7e43bc46555 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/tcpserver.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/template.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/template.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..449d39d1c26844172acecc01d0ff92628106d232 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/template.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/testing.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/testing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d923f140d2569ce82c23eca2578adfa3518c7c31 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/testing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27a70ee0c92892190f89df769a39b176ab8ec655 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/websocket.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/websocket.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8acbb029a4d64f9358807285065dfbf2aa88dba Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/websocket.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/__pycache__/wsgi.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/__pycache__/wsgi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e03ac25eb17251eb5d5761ac69ee4fe83b7e12d1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/__pycache__/wsgi.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/platform/__init__.py b/python/user_packages/Python313/site-packages/tornado/platform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edee0e002de6a0d4446c0b59225b8d38e754c52a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/asyncio.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/asyncio.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c6db45a909e28701ecece56e80978a6bcdf008 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/asyncio.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/caresresolver.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/caresresolver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d78b8a08c2eaf5258bfb336770093547239652e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/caresresolver.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/twisted.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/twisted.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b552de3068b8da08a20e642df2a5abe27a226f39 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/platform/__pycache__/twisted.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/platform/asyncio.py b/python/user_packages/Python313/site-packages/tornado/platform/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..4677fc97fb67b76e33776ee9373f5b5efb7a1017 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/platform/asyncio.py @@ -0,0 +1,753 @@ +"""Bridges between the `asyncio` module and Tornado IOLoop. + +.. versionadded:: 3.2 + +This module integrates Tornado with the ``asyncio`` module introduced +in Python 3.4. This makes it possible to combine the two libraries on +the same event loop. + +.. deprecated:: 5.0 + + While the code in this module is still used, it is now enabled + automatically when `asyncio` is available, so applications should + no longer need to refer to this module directly. + +.. note:: + + Tornado is designed to use a selector-based event loop. On Windows, + where a proactor-based event loop has been the default since Python 3.8, + a selector event loop is emulated by running ``select`` on a separate thread. + Configuring ``asyncio`` to use a selector event loop may improve performance + of Tornado (but may reduce performance of other ``asyncio``-based libraries + in the same process). +""" + +import asyncio +import atexit +import concurrent.futures +import contextvars +import errno +import functools +import select +import socket +import sys +import threading +import typing +import warnings +from tornado.gen import convert_yielded +from tornado.ioloop import IOLoop, _Selectable + +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Protocol, + Set, + Tuple, + TypeVar, + Union, +) + +if typing.TYPE_CHECKING: + from typing_extensions import TypeVarTuple, Unpack + + +class _HasFileno(Protocol): + def fileno(self) -> int: + pass + + +_FileDescriptorLike = Union[int, _HasFileno] + +_T = TypeVar("_T") + +if typing.TYPE_CHECKING: + _Ts = TypeVarTuple("_Ts") + +# Collection of selector thread event loops to shut down on exit. +_selector_loops: Set["SelectorThread"] = set() + + +def _atexit_callback() -> None: + for loop in _selector_loops: + with loop._select_cond: + loop._closing_selector = True + loop._select_cond.notify() + try: + loop._waker_w.send(b"a") + except BlockingIOError: + pass + if loop._thread is not None: + # If we don't join our (daemon) thread here, we may get a deadlock + # during interpreter shutdown. I don't really understand why. This + # deadlock happens every time in CI (both travis and appveyor) but + # I've never been able to reproduce locally. + loop._thread.join() + _selector_loops.clear() + + +atexit.register(_atexit_callback) + + +class BaseAsyncIOLoop(IOLoop): + def initialize( # type: ignore + self, asyncio_loop: asyncio.AbstractEventLoop, **kwargs: Any + ) -> None: + # asyncio_loop is always the real underlying IOLoop. This is used in + # ioloop.py to maintain the asyncio-to-ioloop mappings. + self.asyncio_loop = asyncio_loop + # selector_loop is an event loop that implements the add_reader family of + # methods. Usually the same as asyncio_loop but differs on platforms such + # as windows where the default event loop does not implement these methods. + self.selector_loop = asyncio_loop + if hasattr(asyncio, "ProactorEventLoop") and isinstance( + asyncio_loop, asyncio.ProactorEventLoop + ): + # Ignore this line for mypy because the abstract method checker + # doesn't understand dynamic proxies. + self.selector_loop = AddThreadSelectorEventLoop(asyncio_loop) # type: ignore + # Maps fd to (fileobj, handler function) pair (as in IOLoop.add_handler) + self.handlers: Dict[int, Tuple[Union[int, _Selectable], Callable]] = {} + # Set of fds listening for reads/writes + self.readers: Set[int] = set() + self.writers: Set[int] = set() + self.closing = False + # If an asyncio loop was closed through an asyncio interface + # instead of IOLoop.close(), we'd never hear about it and may + # have left a dangling reference in our map. In case an + # application (or, more likely, a test suite) creates and + # destroys a lot of event loops in this way, check here to + # ensure that we don't have a lot of dead loops building up in + # the map. + # + # TODO(bdarnell): consider making self.asyncio_loop a weakref + # for AsyncIOMainLoop and make _ioloop_for_asyncio a + # WeakKeyDictionary. + for loop in IOLoop._ioloop_for_asyncio.copy(): + if loop.is_closed(): + try: + del IOLoop._ioloop_for_asyncio[loop] + except KeyError: + pass + + # Make sure we don't already have an IOLoop for this asyncio loop + existing_loop = IOLoop._ioloop_for_asyncio.setdefault(asyncio_loop, self) + if existing_loop is not self: + raise RuntimeError( + f"IOLoop {existing_loop} already associated with asyncio loop {asyncio_loop}" + ) + + super().initialize(**kwargs) + + def close(self, all_fds: bool = False) -> None: + self.closing = True + for fd in list(self.handlers): + fileobj, handler_func = self.handlers[fd] + self.remove_handler(fd) + if all_fds: + self.close_fd(fileobj) + # Remove the mapping before closing the asyncio loop. If this + # happened in the other order, we could race against another + # initialize() call which would see the closed asyncio loop, + # assume it was closed from the asyncio side, and do this + # cleanup for us, leading to a KeyError. + del IOLoop._ioloop_for_asyncio[self.asyncio_loop] + if self.selector_loop is not self.asyncio_loop: + self.selector_loop.close() + self.asyncio_loop.close() + + def add_handler( + self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int + ) -> None: + fd, fileobj = self.split_fd(fd) + if fd in self.handlers: + raise ValueError("fd %s added twice" % fd) + self.handlers[fd] = (fileobj, handler) + if events & IOLoop.READ: + self.selector_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) + self.readers.add(fd) + if events & IOLoop.WRITE: + self.selector_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE) + self.writers.add(fd) + + def update_handler(self, fd: Union[int, _Selectable], events: int) -> None: + fd, fileobj = self.split_fd(fd) + if events & IOLoop.READ: + if fd not in self.readers: + self.selector_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) + self.readers.add(fd) + else: + if fd in self.readers: + self.selector_loop.remove_reader(fd) + self.readers.remove(fd) + if events & IOLoop.WRITE: + if fd not in self.writers: + self.selector_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE) + self.writers.add(fd) + else: + if fd in self.writers: + self.selector_loop.remove_writer(fd) + self.writers.remove(fd) + + def remove_handler(self, fd: Union[int, _Selectable]) -> None: + fd, fileobj = self.split_fd(fd) + if fd not in self.handlers: + return + if fd in self.readers: + self.selector_loop.remove_reader(fd) + self.readers.remove(fd) + if fd in self.writers: + self.selector_loop.remove_writer(fd) + self.writers.remove(fd) + del self.handlers[fd] + + def _handle_events(self, fd: int, events: int) -> None: + fileobj, handler_func = self.handlers[fd] + handler_func(fileobj, events) + + def start(self) -> None: + self.asyncio_loop.run_forever() + + def stop(self) -> None: + self.asyncio_loop.stop() + + def call_at( + self, when: float, callback: Callable, *args: Any, **kwargs: Any + ) -> object: + # asyncio.call_at supports *args but not **kwargs, so bind them here. + # We do not synchronize self.time and asyncio_loop.time, so + # convert from absolute to relative. + return self.asyncio_loop.call_later( + max(0, when - self.time()), + self._run_callback, + functools.partial(callback, *args, **kwargs), + ) + + def remove_timeout(self, timeout: object) -> None: + timeout.cancel() # type: ignore + + def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None: + try: + if asyncio.get_running_loop() is self.asyncio_loop: + call_soon = self.asyncio_loop.call_soon + else: + call_soon = self.asyncio_loop.call_soon_threadsafe + except RuntimeError: + call_soon = self.asyncio_loop.call_soon_threadsafe + + try: + call_soon(self._run_callback, functools.partial(callback, *args, **kwargs)) + except RuntimeError: + # "Event loop is closed". Swallow the exception for + # consistency with PollIOLoop (and logical consistency + # with the fact that we can't guarantee that an + # add_callback that completes without error will + # eventually execute). + pass + except AttributeError: + # ProactorEventLoop may raise this instead of RuntimeError + # if call_soon_threadsafe races with a call to close(). + # Swallow it too for consistency. + pass + + def add_callback_from_signal( + self, callback: Callable, *args: Any, **kwargs: Any + ) -> None: + warnings.warn("add_callback_from_signal is deprecated", DeprecationWarning) + try: + self.asyncio_loop.call_soon_threadsafe( + self._run_callback, functools.partial(callback, *args, **kwargs) + ) + except RuntimeError: + pass + + def run_in_executor( + self, + executor: Optional[concurrent.futures.Executor], + func: Callable[..., _T], + *args: Any, + ) -> "asyncio.Future[_T]": + return self.asyncio_loop.run_in_executor(executor, func, *args) + + def set_default_executor(self, executor: concurrent.futures.Executor) -> None: + return self.asyncio_loop.set_default_executor(executor) + + +class AsyncIOMainLoop(BaseAsyncIOLoop): + """``AsyncIOMainLoop`` creates an `.IOLoop` that corresponds to the + current ``asyncio`` event loop (i.e. the one returned by + ``asyncio.get_event_loop()``). + + .. deprecated:: 5.0 + + Now used automatically when appropriate; it is no longer necessary + to refer to this class directly. + + .. versionchanged:: 5.0 + + Closing an `AsyncIOMainLoop` now closes the underlying asyncio loop. + """ + + def initialize(self, **kwargs: Any) -> None: # type: ignore + super().initialize(asyncio.get_event_loop(), **kwargs) + + def _make_current(self) -> None: + # AsyncIOMainLoop already refers to the current asyncio loop so + # nothing to do here. + pass + + +class AsyncIOLoop(BaseAsyncIOLoop): + """``AsyncIOLoop`` is an `.IOLoop` that runs on an ``asyncio`` event loop. + This class follows the usual Tornado semantics for creating new + ``IOLoops``; these loops are not necessarily related to the + ``asyncio`` default event loop. + + Each ``AsyncIOLoop`` creates a new ``asyncio.EventLoop``; this object + can be accessed with the ``asyncio_loop`` attribute. + + .. versionchanged:: 6.2 + + Support explicit ``asyncio_loop`` argument + for specifying the asyncio loop to attach to, + rather than always creating a new one with the default policy. + + .. versionchanged:: 5.0 + + When an ``AsyncIOLoop`` becomes the current `.IOLoop`, it also sets + the current `asyncio` event loop. + + .. deprecated:: 5.0 + + Now used automatically when appropriate; it is no longer necessary + to refer to this class directly. + """ + + def initialize(self, **kwargs: Any) -> None: # type: ignore + self.is_current = False + loop = None + if "asyncio_loop" not in kwargs: + kwargs["asyncio_loop"] = loop = asyncio.new_event_loop() + try: + super().initialize(**kwargs) + except Exception: + # If initialize() does not succeed (taking ownership of the loop), + # we have to close it. + if loop is not None: + loop.close() + raise + + def close(self, all_fds: bool = False) -> None: + if self.is_current: + self._clear_current() + super().close(all_fds=all_fds) + + def _make_current(self) -> None: + if not self.is_current: + try: + self.old_asyncio = asyncio.get_event_loop() + except (RuntimeError, AssertionError): + self.old_asyncio = None # type: ignore + self.is_current = True + asyncio.set_event_loop(self.asyncio_loop) + + def _clear_current_hook(self) -> None: + if self.is_current: + asyncio.set_event_loop(self.old_asyncio) + self.is_current = False + + +def to_tornado_future(asyncio_future: asyncio.Future) -> asyncio.Future: + """Convert an `asyncio.Future` to a `tornado.concurrent.Future`. + + .. versionadded:: 4.1 + + .. deprecated:: 5.0 + Tornado ``Futures`` have been merged with `asyncio.Future`, + so this method is now a no-op. + """ + return asyncio_future + + +def to_asyncio_future(tornado_future: asyncio.Future) -> asyncio.Future: + """Convert a Tornado yieldable object to an `asyncio.Future`. + + .. versionadded:: 4.1 + + .. versionchanged:: 4.3 + Now accepts any yieldable object, not just + `tornado.concurrent.Future`. + + .. deprecated:: 5.0 + Tornado ``Futures`` have been merged with `asyncio.Future`, + so this method is now equivalent to `tornado.gen.convert_yielded`. + """ + return convert_yielded(tornado_future) + + +_AnyThreadEventLoopPolicy = None + + +def __getattr__(name: str) -> typing.Any: + # The event loop policy system is deprecated in Python 3.14; simply accessing + # the name asyncio.DefaultEventLoopPolicy will raise a warning. Lazily create + # the AnyThreadEventLoopPolicy class so that the warning is only raised if + # the policy is used. + if name != "AnyThreadEventLoopPolicy": + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + global _AnyThreadEventLoopPolicy + if _AnyThreadEventLoopPolicy is None: + if sys.platform == "win32" and hasattr( + asyncio, "WindowsSelectorEventLoopPolicy" + ): + # "Any thread" and "selector" should be orthogonal, but there's not a clean + # interface for composing policies so pick the right base. + _BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore + else: + _BasePolicy = asyncio.DefaultEventLoopPolicy + + class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore + """Event loop policy that allows loop creation on any thread. + + The default `asyncio` event loop policy only automatically creates + event loops in the main threads. Other threads must create event + loops explicitly or `asyncio.get_event_loop` (and therefore + `.IOLoop.current`) will fail. Installing this policy allows event + loops to be created automatically on any thread, matching the + behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2). + + Usage:: + + asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy()) + + .. versionadded:: 5.0 + + .. deprecated:: 6.2 + + ``AnyThreadEventLoopPolicy`` affects the implicit creation + of an event loop, which is deprecated in Python 3.10 and + will be removed in a future version of Python. At that time + ``AnyThreadEventLoopPolicy`` will no longer be useful. + If you are relying on it, use `asyncio.new_event_loop` + or `asyncio.run` explicitly in any non-main threads that + need event loops. + """ + + def __init__(self) -> None: + super().__init__() + warnings.warn( + "AnyThreadEventLoopPolicy is deprecated, use asyncio.run " + "or asyncio.new_event_loop instead", + DeprecationWarning, + stacklevel=2, + ) + + def get_event_loop(self) -> asyncio.AbstractEventLoop: + try: + return super().get_event_loop() + except RuntimeError: + # "There is no current event loop in thread %r" + loop = self.new_event_loop() + self.set_event_loop(loop) + return loop + + _AnyThreadEventLoopPolicy = AnyThreadEventLoopPolicy + + return _AnyThreadEventLoopPolicy + + +class SelectorThread: + """Define ``add_reader`` methods to be called in a background select thread. + + Instances of this class start a second thread to run a selector. + This thread is completely hidden from the user; + all callbacks are run on the wrapped event loop's thread. + + Typically used via ``AddThreadSelectorEventLoop``, + but can be attached to a running asyncio loop. + """ + + _closed = False + + def __init__(self, real_loop: asyncio.AbstractEventLoop) -> None: + self._main_thread_ctx = contextvars.copy_context() + + self._real_loop = real_loop + + self._select_cond = threading.Condition() + self._select_args: Optional[ + Tuple[List[_FileDescriptorLike], List[_FileDescriptorLike]] + ] = None + self._closing_selector = False + self._thread: Optional[threading.Thread] = None + self._thread_manager_handle = self._thread_manager() + + async def thread_manager_anext() -> None: + # the anext builtin wasn't added until 3.10. We just need to iterate + # this generator one step. + await self._thread_manager_handle.__anext__() + + # When the loop starts, start the thread. Not too soon because we can't + # clean up if we get to this point but the event loop is closed without + # starting. + self._real_loop.call_soon( + lambda: self._real_loop.create_task(thread_manager_anext()), + context=self._main_thread_ctx, + ) + + self._readers: Dict[_FileDescriptorLike, Callable] = {} + self._writers: Dict[_FileDescriptorLike, Callable] = {} + + # Writing to _waker_w will wake up the selector thread, which + # watches for _waker_r to be readable. + self._waker_r, self._waker_w = socket.socketpair() + self._waker_r.setblocking(False) + self._waker_w.setblocking(False) + _selector_loops.add(self) + self.add_reader(self._waker_r, self._consume_waker) + + def close(self) -> None: + if self._closed: + return + with self._select_cond: + self._closing_selector = True + self._select_cond.notify() + self._wake_selector() + if self._thread is not None: + self._thread.join() + _selector_loops.discard(self) + self.remove_reader(self._waker_r) + self._waker_r.close() + self._waker_w.close() + self._closed = True + + async def _thread_manager(self) -> typing.AsyncGenerator[None, None]: + # Create a thread to run the select system call. We manage this thread + # manually so we can trigger a clean shutdown from an atexit hook. Note + # that due to the order of operations at shutdown, only daemon threads + # can be shut down in this way (non-daemon threads would require the + # introduction of a new hook: https://bugs.python.org/issue41962) + self._thread = threading.Thread( + name="Tornado selector", + daemon=True, + target=self._run_select, + ) + self._thread.start() + self._start_select() + try: + # The presense of this yield statement means that this coroutine + # is actually an asynchronous generator, which has a special + # shutdown protocol. We wait at this yield point until the + # event loop's shutdown_asyncgens method is called, at which point + # we will get a GeneratorExit exception and can shut down the + # selector thread. + yield + except GeneratorExit: + self.close() + raise + + def _wake_selector(self) -> None: + if self._closed: + return + try: + self._waker_w.send(b"a") + except BlockingIOError: + pass + + def _consume_waker(self) -> None: + try: + self._waker_r.recv(1024) + except BlockingIOError: + pass + + def _start_select(self) -> None: + # Capture reader and writer sets here in the event loop + # thread to avoid any problems with concurrent + # modification while the select loop uses them. + with self._select_cond: + assert self._select_args is None + self._select_args = (list(self._readers.keys()), list(self._writers.keys())) + self._select_cond.notify() + + def _run_select(self) -> None: + while True: + with self._select_cond: + while self._select_args is None and not self._closing_selector: + self._select_cond.wait() + if self._closing_selector: + return + assert self._select_args is not None + to_read, to_write = self._select_args + self._select_args = None + + # We use the simpler interface of the select module instead of + # the more stateful interface in the selectors module because + # this class is only intended for use on windows, where + # select.select is the only option. The selector interface + # does not have well-documented thread-safety semantics that + # we can rely on so ensuring proper synchronization would be + # tricky. + try: + # On windows, selecting on a socket for write will not + # return the socket when there is an error (but selecting + # for reads works). Also select for errors when selecting + # for writes, and merge the results. + # + # This pattern is also used in + # https://github.com/python/cpython/blob/v3.8.0/Lib/selectors.py#L312-L317 + rs, ws, xs = select.select(to_read, to_write, to_write) + ws = ws + xs + except OSError as e: + # After remove_reader or remove_writer is called, the file + # descriptor may subsequently be closed on the event loop + # thread. It's possible that this select thread hasn't + # gotten into the select system call by the time that + # happens in which case (at least on macOS), select may + # raise a "bad file descriptor" error. If we get that + # error, check and see if we're also being woken up by + # polling the waker alone. If we are, just return to the + # event loop and we'll get the updated set of file + # descriptors on the next iteration. Otherwise, raise the + # original error. + if e.errno == getattr(errno, "WSAENOTSOCK", errno.EBADF): + rs, _, _ = select.select([self._waker_r.fileno()], [], [], 0) + if rs: + ws = [] + else: + raise + else: + raise + + try: + self._real_loop.call_soon_threadsafe( + self._handle_select, rs, ws, context=self._main_thread_ctx + ) + except RuntimeError: + # "Event loop is closed". Swallow the exception for + # consistency with PollIOLoop (and logical consistency + # with the fact that we can't guarantee that an + # add_callback that completes without error will + # eventually execute). + pass + except AttributeError: + # ProactorEventLoop may raise this instead of RuntimeError + # if call_soon_threadsafe races with a call to close(). + # Swallow it too for consistency. + pass + + def _handle_select( + self, rs: List[_FileDescriptorLike], ws: List[_FileDescriptorLike] + ) -> None: + for r in rs: + self._handle_event(r, self._readers) + for w in ws: + self._handle_event(w, self._writers) + self._start_select() + + def _handle_event( + self, + fd: _FileDescriptorLike, + cb_map: Dict[_FileDescriptorLike, Callable], + ) -> None: + try: + callback = cb_map[fd] + except KeyError: + return + callback() + + def add_reader( + self, fd: _FileDescriptorLike, callback: Callable[..., None], *args: Any + ) -> None: + self._readers[fd] = functools.partial(callback, *args) + self._wake_selector() + + def add_writer( + self, fd: _FileDescriptorLike, callback: Callable[..., None], *args: Any + ) -> None: + self._writers[fd] = functools.partial(callback, *args) + self._wake_selector() + + def remove_reader(self, fd: _FileDescriptorLike) -> bool: + try: + del self._readers[fd] + except KeyError: + return False + self._wake_selector() + return True + + def remove_writer(self, fd: _FileDescriptorLike) -> bool: + try: + del self._writers[fd] + except KeyError: + return False + self._wake_selector() + return True + + +class AddThreadSelectorEventLoop(asyncio.AbstractEventLoop): + """Wrap an event loop to add implementations of the ``add_reader`` method family. + + Instances of this class start a second thread to run a selector. + This thread is completely hidden from the user; all callbacks are + run on the wrapped event loop's thread. + + This class is used automatically by Tornado; applications should not need + to refer to it directly. + + It is safe to wrap any event loop with this class, although it only makes sense + for event loops that do not implement the ``add_reader`` family of methods + themselves (i.e. ``WindowsProactorEventLoop``) + + Closing the ``AddThreadSelectorEventLoop`` also closes the wrapped event loop. + + """ + + # This class is a __getattribute__-based proxy. All attributes other than those + # in this set are proxied through to the underlying loop. + MY_ATTRIBUTES = { + "_real_loop", + "_selector", + "add_reader", + "add_writer", + "close", + "remove_reader", + "remove_writer", + } + + def __getattribute__(self, name: str) -> Any: + if name in AddThreadSelectorEventLoop.MY_ATTRIBUTES: + return super().__getattribute__(name) + return getattr(self._real_loop, name) + + def __init__(self, real_loop: asyncio.AbstractEventLoop) -> None: + self._real_loop = real_loop + self._selector = SelectorThread(real_loop) + + def close(self) -> None: + self._selector.close() + self._real_loop.close() + + def add_reader( + self, + fd: "_FileDescriptorLike", + callback: Callable[..., None], + *args: "Unpack[_Ts]", + ) -> None: + return self._selector.add_reader(fd, callback, *args) + + def add_writer( + self, + fd: "_FileDescriptorLike", + callback: Callable[..., None], + *args: "Unpack[_Ts]", + ) -> None: + return self._selector.add_writer(fd, callback, *args) + + def remove_reader(self, fd: "_FileDescriptorLike") -> bool: + return self._selector.remove_reader(fd) + + def remove_writer(self, fd: "_FileDescriptorLike") -> bool: + return self._selector.remove_writer(fd) diff --git a/python/user_packages/Python313/site-packages/tornado/platform/caresresolver.py b/python/user_packages/Python313/site-packages/tornado/platform/caresresolver.py new file mode 100644 index 0000000000000000000000000000000000000000..8d47221871f780f5817ed340af97c6bad09a491f --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/platform/caresresolver.py @@ -0,0 +1,94 @@ +import pycares # type: ignore +import socket + +from tornado.concurrent import Future +from tornado import gen +from tornado.ioloop import IOLoop +from tornado.netutil import Resolver, is_valid_ip + +import typing + +if typing.TYPE_CHECKING: + from typing import Generator, Any, List, Tuple, Dict # noqa: F401 + + +class CaresResolver(Resolver): + """Name resolver based on the c-ares library. + + This is a non-blocking and non-threaded resolver. It may not produce the + same results as the system resolver, but can be used for non-blocking + resolution when threads cannot be used. + + ``pycares`` will not return a mix of ``AF_INET`` and ``AF_INET6`` when + ``family`` is ``AF_UNSPEC``, so it is only recommended for use in + ``AF_INET`` (i.e. IPv4). This is the default for + ``tornado.simple_httpclient``, but other libraries may default to + ``AF_UNSPEC``. + + .. versionchanged:: 5.0 + The ``io_loop`` argument (deprecated since version 4.1) has been removed. + + .. deprecated:: 6.2 + This class is deprecated and will be removed in Tornado 7.0. Use the default + thread-based resolver instead. + """ + + def initialize(self) -> None: + self.io_loop = IOLoop.current() + self.channel = pycares.Channel(sock_state_cb=self._sock_state_cb) + self.fds = {} # type: Dict[int, int] + + def _sock_state_cb(self, fd: int, readable: bool, writable: bool) -> None: + state = (IOLoop.READ if readable else 0) | (IOLoop.WRITE if writable else 0) + if not state: + self.io_loop.remove_handler(fd) + del self.fds[fd] + elif fd in self.fds: + self.io_loop.update_handler(fd, state) + self.fds[fd] = state + else: + self.io_loop.add_handler(fd, self._handle_events, state) + self.fds[fd] = state + + def _handle_events(self, fd: int, events: int) -> None: + read_fd = pycares.ARES_SOCKET_BAD + write_fd = pycares.ARES_SOCKET_BAD + if events & IOLoop.READ: + read_fd = fd + if events & IOLoop.WRITE: + write_fd = fd + self.channel.process_fd(read_fd, write_fd) + + @gen.coroutine + def resolve( + self, host: str, port: int, family: int = 0 + ) -> "Generator[Any, Any, List[Tuple[int, Any]]]": + if is_valid_ip(host): + addresses = [host] + else: + # gethostbyname doesn't take callback as a kwarg + fut = Future() # type: Future[Tuple[Any, Any]] + self.channel.gethostbyname( + host, family, lambda result, error: fut.set_result((result, error)) + ) + result, error = yield fut + if error: + raise OSError( + "C-Ares returned error %s: %s while resolving %s" + % (error, pycares.errno.strerror(error), host) + ) + addresses = result.addresses + addrinfo = [] + for address in addresses: + if "." in address: + address_family = socket.AF_INET + elif ":" in address: + address_family = socket.AF_INET6 + else: + address_family = socket.AF_UNSPEC + if family != socket.AF_UNSPEC and family != address_family: + raise OSError( + "Requested socket family %d but got %d" % (family, address_family) + ) + addrinfo.append((typing.cast(int, address_family), (address, port))) + return addrinfo diff --git a/python/user_packages/Python313/site-packages/tornado/platform/twisted.py b/python/user_packages/Python313/site-packages/tornado/platform/twisted.py new file mode 100644 index 0000000000000000000000000000000000000000..be7140f01f6cee726ebf38fcb5aab7e41e9aaaf8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/platform/twisted.py @@ -0,0 +1,64 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +"""Bridges between the Twisted package and Tornado.""" + +import sys + +from twisted.internet.defer import Deferred # type: ignore +from twisted.python import failure # type: ignore + +from tornado.concurrent import Future, future_set_exc_info +from tornado import gen + +import typing # noqa: F401 + + +def install() -> None: + """Install ``AsyncioSelectorReactor`` as the default Twisted reactor. + + .. deprecated:: 5.1 + + This function is provided for backwards compatibility; code + that does not require compatibility with older versions of + Tornado should use + ``twisted.internet.asyncioreactor.install()`` directly. + + .. versionchanged:: 6.0.3 + + In Tornado 5.x and before, this function installed a reactor + based on the Tornado ``IOLoop``. When that reactor + implementation was removed in Tornado 6.0.0, this function was + removed as well. It was restored in Tornado 6.0.3 using the + ``asyncio`` reactor instead. + + """ + from twisted.internet.asyncioreactor import install # type: ignore + + install() + + +if hasattr(gen.convert_yielded, "register"): + + @gen.convert_yielded.register(Deferred) + def _(d: Deferred) -> Future: + f = Future() # type: Future[typing.Any] + + def errback(failure: failure.Failure) -> None: + try: + failure.raiseException() + # Should never happen, but just in case + raise Exception("errback called without error") + except: + future_set_exc_info(f, sys.exc_info()) + + d.addCallbacks(f.set_result, errback) + return f diff --git a/python/user_packages/Python313/site-packages/tornado/test/__init__.py b/python/user_packages/Python313/site-packages/tornado/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/tornado/test/__main__.py b/python/user_packages/Python313/site-packages/tornado/test/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..d01d022ce1b843ecd66bec86eddcf5979dfe7a4f --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/__main__.py @@ -0,0 +1,11 @@ +"""Shim to allow python -m tornado.test. +""" + +from tornado.test.runtests import all, main + +# tornado.testing.main autodiscovery relies on 'all' being present in +# the main module, so import it here even though it is not used directly. +# The following line prevents a pyflakes warning. +all = all + +main() diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9e33447f5f22c1bb1c191a2898695e4236f25b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__main__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..476e7b2da62b965054dc610e5367ea933f79800d Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/__main__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/asyncio_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/asyncio_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b81c697042ccb753227b1c79f54c0f501658631a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/asyncio_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/auth_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/auth_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7454b586f3aef60b39ec7f68f18e2302392c424c Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/auth_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/autoreload_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/autoreload_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b0ed10e3a2fa186017767cc959513f89aebf43e Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/autoreload_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/circlerefs_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/circlerefs_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b791b0b011c9bccc1c97335a3c13c3cc65606fd Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/circlerefs_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/concurrent_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/concurrent_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d39326602e20abb11d7139bc46450d5f9cb9a97a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/concurrent_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/curl_httpclient_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/curl_httpclient_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69827164efbdcec681c00b339f7f1004999425ac Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/curl_httpclient_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/escape_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/escape_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11b81b2c6a863ca418ca1b894e132194b9ed0677 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/escape_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/gen_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/gen_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96c0e44eecb6f6e9cf646116ef994f8150c1bff9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/gen_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/http1connection_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/http1connection_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d0c7e81e99396f7b3785ba658d7dd2bb1b94bef Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/http1connection_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpclient_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpclient_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95dcd9d6f45c880f05c0313a5fa5c1103d1f16fe Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpclient_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpserver_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpserver_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01eec5594f7a63506bbebceaef019a388794e648 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httpserver_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httputil_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httputil_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f5ae37a412546d595872fd97250dad16b696808 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/httputil_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/import_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/import_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee4cbae8ca93333c1c6ef9bfbc3e16da790da106 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/import_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/ioloop_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/ioloop_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc21382b348e3646682acf278aaaed8c0f35d2b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/ioloop_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/iostream_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/iostream_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a7155820e900aa05b728beeb17d58549c58ba1f Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/iostream_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locale_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locale_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39230a119b1179650365cb5956bf435a77fbdbb7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locale_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locks_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locks_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3b17fc0e4d250333149b2a913a06ab408373b00 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/locks_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/log_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/log_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f2c532403d42c6a6c014946ca9ce78ec605954b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/log_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/netutil_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/netutil_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df036ff812bf6829d5e18594be2f1a76067fb822 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/netutil_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/options_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/options_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25645ba0ef3ac2db892b459a5d4c9900360e0cce Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/options_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/process_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/process_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e02a7e8c23e2cc751ea2ae252a5d96a78011a30 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/process_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/queues_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/queues_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04e39151fe48dac0c4c72a7e58bd09d1477042f6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/queues_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/resolve_test_helper.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/resolve_test_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3387a1ad39f09fa9807d21f88f3563cc21ca7028 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/resolve_test_helper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/routing_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/routing_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd65f5eb0d4eee3f352f20eaf1747a01ae1ce369 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/routing_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/runtests.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/runtests.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..939e611ce6d8a3bac0b7140f5af4da1fd9168501 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/runtests.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/simple_httpclient_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/simple_httpclient_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b42a6d582eb421a8fb5f48478d99025483738302 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/simple_httpclient_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpclient_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpclient_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7958e561d15ef641e3ace76d47f1aa794cc1a836 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpclient_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpserver_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpserver_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad82fb60e5cf27da935a9640a4879d00e22cec35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/tcpserver_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/template_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/template_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c13805e5072470cd1fa673ded87b4db30ae2e15 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/template_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/testing_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/testing_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac9f07c7e3eaeb10b00ecf084cfbca4eccea825b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/testing_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/twisted_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/twisted_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56fab464ed197c7f2bb493dd214d2958ca39ecf6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/twisted_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2bcd63a94929049b3e74cf6b11d08c11d3afc4b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85e33e12ac4bdbee8d558fe7b4477b13350c84e0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/util_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/websocket_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/websocket_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e87556a5a805226a890a6d1e130def7d8cb61db Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/websocket_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/__pycache__/wsgi_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/wsgi_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abe7306c12de4b45c2f68791acffe72151884099 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/__pycache__/wsgi_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/asyncio_test.py b/python/user_packages/Python313/site-packages/tornado/test/asyncio_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4025117bd8f401e52b73d13bb5dd2f548e6066b4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/asyncio_test.py @@ -0,0 +1,298 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import asyncio +import contextvars +import threading +import time +import unittest +import warnings + +from concurrent.futures import ThreadPoolExecutor +import tornado.platform.asyncio +from tornado import gen +from tornado.ioloop import IOLoop +from tornado.platform.asyncio import ( + AsyncIOLoop, + to_asyncio_future, + AddThreadSelectorEventLoop, +) +from tornado.testing import ( + AsyncTestCase, + gen_test, + setup_with_context_manager, + AsyncHTTPTestCase, +) +from tornado.test.util import ignore_deprecation +from tornado.web import Application, RequestHandler + + +class AsyncIOLoopTest(AsyncTestCase): + @property + def asyncio_loop(self): + return self.io_loop.asyncio_loop # type: ignore + + def test_asyncio_callback(self): + # Basic test that the asyncio loop is set up correctly. + async def add_callback(): + asyncio.get_event_loop().call_soon(self.stop) + + self.asyncio_loop.run_until_complete(add_callback()) + self.wait() + + @gen_test + def test_asyncio_future(self): + # Test that we can yield an asyncio future from a tornado coroutine. + # Without 'yield from', we must wrap coroutines in ensure_future. + x = yield asyncio.ensure_future( + asyncio.get_event_loop().run_in_executor(None, lambda: 42) + ) + self.assertEqual(x, 42) + + @gen_test + def test_asyncio_yield_from(self): + @gen.coroutine + def f(): + event_loop = asyncio.get_event_loop() + x = yield from event_loop.run_in_executor(None, lambda: 42) + return x + + result = yield f() + self.assertEqual(result, 42) + + def test_asyncio_adapter(self): + # This test demonstrates that when using the asyncio coroutine + # runner (i.e. run_until_complete), the to_asyncio_future + # adapter is needed. No adapter is needed in the other direction, + # as demonstrated by other tests in the package. + @gen.coroutine + def tornado_coroutine(): + yield gen.moment + raise gen.Return(42) + + async def native_coroutine_without_adapter(): + return await tornado_coroutine() + + async def native_coroutine_with_adapter(): + return await to_asyncio_future(tornado_coroutine()) + + # Use the adapter, but two degrees from the tornado coroutine. + async def native_coroutine_with_adapter2(): + return await to_asyncio_future(native_coroutine_without_adapter()) + + # Tornado supports native coroutines both with and without adapters + self.assertEqual(self.io_loop.run_sync(native_coroutine_without_adapter), 42) + self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter), 42) + self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter2), 42) + + # Asyncio only supports coroutines that yield asyncio-compatible + # Futures (which our Future is since 5.0). + self.assertEqual( + self.asyncio_loop.run_until_complete(native_coroutine_without_adapter()), + 42, + ) + self.assertEqual( + self.asyncio_loop.run_until_complete(native_coroutine_with_adapter()), + 42, + ) + self.assertEqual( + self.asyncio_loop.run_until_complete(native_coroutine_with_adapter2()), + 42, + ) + + def test_add_thread_close_idempotent(self): + loop = AddThreadSelectorEventLoop(asyncio.get_event_loop()) # type: ignore + loop.close() + loop.close() + + +class LeakTest(unittest.TestCase): + def setUp(self): + # Trigger a cleanup of the mapping so we start with a clean slate. + AsyncIOLoop(make_current=False).close() + + def tearDown(self): + try: + loop = asyncio.get_event_loop_policy().get_event_loop() + except Exception: + # We may not have a current event loop at this point. + pass + else: + loop.close() + + def test_ioloop_close_leak(self): + orig_count = len(IOLoop._ioloop_for_asyncio) + for i in range(10): + # Create and close an AsyncIOLoop using Tornado interfaces. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + loop = AsyncIOLoop() + loop.close() + new_count = len(IOLoop._ioloop_for_asyncio) - orig_count + self.assertEqual(new_count, 0) + + def test_asyncio_close_leak(self): + orig_count = len(IOLoop._ioloop_for_asyncio) + for i in range(10): + # Create and close an AsyncIOMainLoop using asyncio interfaces. + loop = asyncio.new_event_loop() + loop.call_soon(IOLoop.current) + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + new_count = len(IOLoop._ioloop_for_asyncio) - orig_count + # Because the cleanup is run on new loop creation, we have one + # dangling entry in the map (but only one). + self.assertEqual(new_count, 1) + + +class SelectorThreadLeakTest(unittest.TestCase): + # These tests are only relevant on windows, but they should pass anywhere. + def setUp(self): + # As a precaution, ensure that we've run an event loop at least once + # so if it spins up any singleton threads they're already there. + asyncio.run(self.dummy_tornado_coroutine()) + self.orig_thread_count = threading.active_count() + + def assert_no_thread_leak(self): + # For some reason we see transient failures here, but I haven't been able + # to catch it to identify which thread is causing it. Whatever thread it + # is, it appears to quickly clean up on its own, so just retry a few times. + # At least some of the time the errant thread was running at the time we + # captured self.orig_thread_count, so use inequalities. + deadline = time.time() + 1 + while time.time() < deadline: + threads = list(threading.enumerate()) + if len(threads) <= self.orig_thread_count: + break + time.sleep(0.1) + self.assertLessEqual(len(threads), self.orig_thread_count, threads) + + async def dummy_tornado_coroutine(self): + # Just access the IOLoop to initialize the selector thread. + IOLoop.current() + + def test_asyncio_run(self): + for i in range(10): + # asyncio.run calls shutdown_asyncgens for us. + asyncio.run(self.dummy_tornado_coroutine()) + self.assert_no_thread_leak() + + def test_asyncio_manual(self): + for i in range(10): + loop = asyncio.new_event_loop() + loop.run_until_complete(self.dummy_tornado_coroutine()) + # Without this step, we'd leak the thread. + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.close() + self.assert_no_thread_leak() + + def test_tornado(self): + for i in range(10): + # The IOLoop interfaces are aware of the selector thread and + # (synchronously) shut it down. + loop = IOLoop(make_current=False) + loop.run_sync(self.dummy_tornado_coroutine) + loop.close() + self.assert_no_thread_leak() + + +class AnyThreadEventLoopPolicyTest(unittest.TestCase): + def setUp(self): + setup_with_context_manager(self, ignore_deprecation()) + # Referencing the event loop policy attributes raises deprecation warnings, + # so instead of importing this at the top of the file we capture it here. + self.AnyThreadEventLoopPolicy = ( + tornado.platform.asyncio.AnyThreadEventLoopPolicy + ) + self.orig_policy = asyncio.get_event_loop_policy() + self.executor = ThreadPoolExecutor(1) + + def tearDown(self): + asyncio.set_event_loop_policy(self.orig_policy) + self.executor.shutdown() + + def get_event_loop_on_thread(self): + def get_and_close_event_loop(): + """Get the event loop. Close it if one is returned. + + Returns the (closed) event loop. This is a silly thing + to do and leaves the thread in a broken state, but it's + enough for this test. Closing the loop avoids resource + leak warnings. + """ + loop = asyncio.get_event_loop() + loop.close() + return loop + + future = self.executor.submit(get_and_close_event_loop) + return future.result() + + def test_asyncio_accessor(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + # With the default policy, non-main threads don't get an event + # loop. + self.assertRaises( + RuntimeError, self.executor.submit(asyncio.get_event_loop).result + ) + # Set the policy and we can get a loop. + asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy()) + self.assertIsInstance( + self.executor.submit(asyncio.get_event_loop).result(), + asyncio.AbstractEventLoop, + ) + # Clean up to silence leak warnings. Always use asyncio since + # IOLoop doesn't (currently) close the underlying loop. + self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore + + def test_tornado_accessor(self): + # Tornado's IOLoop.current() API can create a loop for any thread, + # regardless of this event loop policy. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop) + # Clean up to silence leak warnings. Always use asyncio since + # IOLoop doesn't (currently) close the underlying loop. + self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore + + asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy()) + self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop) + self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore + + +class SelectorThreadContextvarsTest(AsyncHTTPTestCase): + ctx_value = "foo" + test_endpoint = "/" + tornado_test_ctx = contextvars.ContextVar("tornado_test_ctx", default="default") + tornado_test_ctx.set(ctx_value) + + def get_app(self) -> Application: + tornado_test_ctx = self.tornado_test_ctx + + class Handler(RequestHandler): + async def get(self): + # On the Windows platform, + # when a asyncio.events.Handle is created + # in the SelectorThread without providing a context, + # it will copy the current thread's context, + # which can lead to the loss of the main thread's context + # when executing the handle. + # Therefore, it is necessary to + # save a copy of the main thread's context in the SelectorThread + # for creating the handle. + self.write(tornado_test_ctx.get()) + + return Application([(self.test_endpoint, Handler)]) + + def test_context_vars(self): + self.assertEqual(self.ctx_value, self.fetch(self.test_endpoint).body.decode()) diff --git a/python/user_packages/Python313/site-packages/tornado/test/auth_test.py b/python/user_packages/Python313/site-packages/tornado/test/auth_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5c066360cacef396fb152081755b36e76d043d24 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/auth_test.py @@ -0,0 +1,608 @@ +# These tests do not currently do much to verify the correct implementation +# of the openid/oauth protocols, they just exercise the major code paths +# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in +# python 3) + +import unittest + +from tornado.auth import ( + OpenIdMixin, + OAuthMixin, + OAuth2Mixin, + GoogleOAuth2Mixin, + FacebookGraphMixin, + TwitterMixin, +) +from tornado.escape import json_decode +from tornado import gen +from tornado.httpclient import HTTPClientError +from tornado.httputil import url_concat +from tornado.log import app_log +from tornado.testing import AsyncHTTPTestCase, ExpectLog +from tornado.web import RequestHandler, Application, HTTPError + +try: + from unittest import mock +except ImportError: + mock = None # type: ignore + + +class OpenIdClientLoginHandler(RequestHandler, OpenIdMixin): + def initialize(self, test): + self._OPENID_ENDPOINT = test.get_url("/openid/server/authenticate") + + @gen.coroutine + def get(self): + if self.get_argument("openid.mode", None): + user = yield self.get_authenticated_user( + http_client=self.settings["http_client"] + ) + if user is None: + raise Exception("user is None") + self.finish(user) + return + res = self.authenticate_redirect() # type: ignore + assert res is None + + +class OpenIdServerAuthenticateHandler(RequestHandler): + def post(self): + if self.get_argument("openid.mode") != "check_authentication": + raise Exception("incorrect openid.mode %r") + self.write("is_valid:true") + + +class OAuth1ClientLoginHandler(RequestHandler, OAuthMixin): + def initialize(self, test, version): + self._OAUTH_VERSION = version + self._OAUTH_REQUEST_TOKEN_URL = test.get_url("/oauth1/server/request_token") + self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth1/server/authorize") + self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/oauth1/server/access_token") + + def _oauth_consumer_token(self): + return dict(key="asdf", secret="qwer") + + @gen.coroutine + def get(self): + if self.get_argument("oauth_token", None): + user = yield self.get_authenticated_user( + http_client=self.settings["http_client"] + ) + if user is None: + raise Exception("user is None") + self.finish(user) + return + yield self.authorize_redirect(http_client=self.settings["http_client"]) + + @gen.coroutine + def _oauth_get_user_future(self, access_token): + if self.get_argument("fail_in_get_user", None): + raise Exception("failing in get_user") + if access_token != dict(key="uiop", secret="5678"): + raise Exception("incorrect access token %r" % access_token) + return dict(email="foo@example.com") + + +class OAuth1ClientLoginCoroutineHandler(OAuth1ClientLoginHandler): + """Replaces OAuth1ClientLoginCoroutineHandler's get() with a coroutine.""" + + @gen.coroutine + def get(self): + if self.get_argument("oauth_token", None): + # Ensure that any exceptions are set on the returned Future, + # not simply thrown into the surrounding StackContext. + try: + yield self.get_authenticated_user() + except Exception as e: + self.set_status(503) + self.write("got exception: %s" % e) + else: + yield self.authorize_redirect() + + +class OAuth1ClientRequestParametersHandler(RequestHandler, OAuthMixin): + def initialize(self, version): + self._OAUTH_VERSION = version + + def _oauth_consumer_token(self): + return dict(key="asdf", secret="qwer") + + def get(self): + params = self._oauth_request_parameters( + "http://www.example.com/api/asdf", + dict(key="uiop", secret="5678"), + parameters=dict(foo="bar"), + ) + self.write(params) + + +class OAuth1ServerRequestTokenHandler(RequestHandler): + def get(self): + self.write("oauth_token=zxcv&oauth_token_secret=1234") + + +class OAuth1ServerAccessTokenHandler(RequestHandler): + def get(self): + self.write("oauth_token=uiop&oauth_token_secret=5678") + + +class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin): + def initialize(self, test): + self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth2/server/authorize") + + def get(self): + res = self.authorize_redirect() # type: ignore + assert res is None + + +class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin): + def initialize(self, test): + self._OAUTH_AUTHORIZE_URL = test.get_url("/facebook/server/authorize") + self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/facebook/server/access_token") + self._FACEBOOK_BASE_URL = test.get_url("/facebook/server") + + @gen.coroutine + def get(self): + if self.get_argument("code", None): + user = yield self.get_authenticated_user( + redirect_uri=self.request.full_url(), + client_id=self.settings["facebook_api_key"], + client_secret=self.settings["facebook_secret"], + code=self.get_argument("code"), + ) + self.write(user) + else: + self.authorize_redirect( + redirect_uri=self.request.full_url(), + client_id=self.settings["facebook_api_key"], + extra_params={"scope": "read_stream,offline_access"}, + ) + + +class FacebookServerAccessTokenHandler(RequestHandler): + def get(self): + self.write(dict(access_token="asdf", expires_in=3600)) + + +class FacebookServerMeHandler(RequestHandler): + def get(self): + self.write("{}") + + +class TwitterClientHandler(RequestHandler, TwitterMixin): + def initialize(self, test): + self._OAUTH_REQUEST_TOKEN_URL = test.get_url("/oauth1/server/request_token") + self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/twitter/server/access_token") + self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth1/server/authorize") + self._OAUTH_AUTHENTICATE_URL = test.get_url("/twitter/server/authenticate") + self._TWITTER_BASE_URL = test.get_url("/twitter/api") + + def get_auth_http_client(self): + return self.settings["http_client"] + + +class TwitterClientLoginHandler(TwitterClientHandler): + @gen.coroutine + def get(self): + if self.get_argument("oauth_token", None): + user = yield self.get_authenticated_user() + if user is None: + raise Exception("user is None") + self.finish(user) + return + yield self.authorize_redirect() + + +class TwitterClientAuthenticateHandler(TwitterClientHandler): + # Like TwitterClientLoginHandler, but uses authenticate_redirect + # instead of authorize_redirect. + @gen.coroutine + def get(self): + if self.get_argument("oauth_token", None): + user = yield self.get_authenticated_user() + if user is None: + raise Exception("user is None") + self.finish(user) + return + yield self.authenticate_redirect() + + +class TwitterClientLoginGenCoroutineHandler(TwitterClientHandler): + @gen.coroutine + def get(self): + if self.get_argument("oauth_token", None): + user = yield self.get_authenticated_user() + self.finish(user) + else: + # New style: with @gen.coroutine the result must be yielded + # or else the request will be auto-finished too soon. + yield self.authorize_redirect() + + +class TwitterClientShowUserHandler(TwitterClientHandler): + @gen.coroutine + def get(self): + # TODO: would be nice to go through the login flow instead of + # cheating with a hard-coded access token. + try: + response = yield self.twitter_request( + "/users/show/%s" % self.get_argument("name"), + access_token=dict(key="hjkl", secret="vbnm"), + ) + except HTTPClientError: + # TODO(bdarnell): Should we catch HTTP errors and + # transform some of them (like 403s) into AuthError? + self.set_status(500) + self.finish("error from twitter request") + else: + self.finish(response) + + +class TwitterServerAccessTokenHandler(RequestHandler): + def get(self): + self.write("oauth_token=hjkl&oauth_token_secret=vbnm&screen_name=foo") + + +class TwitterServerShowUserHandler(RequestHandler): + def get(self, screen_name): + if screen_name == "error": + raise HTTPError(500) + assert "oauth_nonce" in self.request.arguments + assert "oauth_timestamp" in self.request.arguments + assert "oauth_signature" in self.request.arguments + assert self.get_argument("oauth_consumer_key") == "test_twitter_consumer_key" + assert self.get_argument("oauth_signature_method") == "HMAC-SHA1" + assert self.get_argument("oauth_version") == "1.0" + assert self.get_argument("oauth_token") == "hjkl" + self.write(dict(screen_name=screen_name, name=screen_name.capitalize())) + + +class TwitterServerVerifyCredentialsHandler(RequestHandler): + def get(self): + assert "oauth_nonce" in self.request.arguments + assert "oauth_timestamp" in self.request.arguments + assert "oauth_signature" in self.request.arguments + assert self.get_argument("oauth_consumer_key") == "test_twitter_consumer_key" + assert self.get_argument("oauth_signature_method") == "HMAC-SHA1" + assert self.get_argument("oauth_version") == "1.0" + assert self.get_argument("oauth_token") == "hjkl" + self.write(dict(screen_name="foo", name="Foo")) + + +class AuthTest(AsyncHTTPTestCase): + def get_app(self): + return Application( + [ + # test endpoints + ("/openid/client/login", OpenIdClientLoginHandler, dict(test=self)), + ( + "/oauth10/client/login", + OAuth1ClientLoginHandler, + dict(test=self, version="1.0"), + ), + ( + "/oauth10/client/request_params", + OAuth1ClientRequestParametersHandler, + dict(version="1.0"), + ), + ( + "/oauth10a/client/login", + OAuth1ClientLoginHandler, + dict(test=self, version="1.0a"), + ), + ( + "/oauth10a/client/login_coroutine", + OAuth1ClientLoginCoroutineHandler, + dict(test=self, version="1.0a"), + ), + ( + "/oauth10a/client/request_params", + OAuth1ClientRequestParametersHandler, + dict(version="1.0a"), + ), + ("/oauth2/client/login", OAuth2ClientLoginHandler, dict(test=self)), + ("/facebook/client/login", FacebookClientLoginHandler, dict(test=self)), + ("/twitter/client/login", TwitterClientLoginHandler, dict(test=self)), + ( + "/twitter/client/authenticate", + TwitterClientAuthenticateHandler, + dict(test=self), + ), + ( + "/twitter/client/login_gen_coroutine", + TwitterClientLoginGenCoroutineHandler, + dict(test=self), + ), + ( + "/twitter/client/show_user", + TwitterClientShowUserHandler, + dict(test=self), + ), + # simulated servers + ("/openid/server/authenticate", OpenIdServerAuthenticateHandler), + ("/oauth1/server/request_token", OAuth1ServerRequestTokenHandler), + ("/oauth1/server/access_token", OAuth1ServerAccessTokenHandler), + ("/facebook/server/access_token", FacebookServerAccessTokenHandler), + ("/facebook/server/me", FacebookServerMeHandler), + ("/twitter/server/access_token", TwitterServerAccessTokenHandler), + (r"/twitter/api/users/show/(.*)\.json", TwitterServerShowUserHandler), + ( + r"/twitter/api/account/verify_credentials\.json", + TwitterServerVerifyCredentialsHandler, + ), + ], + http_client=self.http_client, + twitter_consumer_key="test_twitter_consumer_key", + twitter_consumer_secret="test_twitter_consumer_secret", + facebook_api_key="test_facebook_api_key", + facebook_secret="test_facebook_secret", + ) + + def test_openid_redirect(self): + response = self.fetch("/openid/client/login", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertIn("/openid/server/authenticate?", response.headers["Location"]) + + def test_openid_get_user(self): + response = self.fetch( + "/openid/client/login?openid.mode=blah" + "&openid.ns.ax=http://openid.net/srv/ax/1.0" + "&openid.ax.type.email=http://axschema.org/contact/email" + "&openid.ax.value.email=foo@example.com" + ) + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual(parsed["email"], "foo@example.com") + + def test_oauth10_redirect(self): + response = self.fetch("/oauth10/client/login", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertTrue( + response.headers["Location"].endswith( + "/oauth1/server/authorize?oauth_token=zxcv" + ) + ) + # the cookie is base64('zxcv')|base64('1234') + self.assertIn( + '_oauth_request_token="enhjdg==|MTIzNA=="', + response.headers["Set-Cookie"], + response.headers["Set-Cookie"], + ) + + def test_oauth10_get_user(self): + response = self.fetch( + "/oauth10/client/login?oauth_token=zxcv", + headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="}, + ) + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual(parsed["email"], "foo@example.com") + self.assertEqual(parsed["access_token"], dict(key="uiop", secret="5678")) + + def test_oauth10_request_parameters(self): + response = self.fetch("/oauth10/client/request_params") + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual(parsed["oauth_consumer_key"], "asdf") + self.assertEqual(parsed["oauth_token"], "uiop") + self.assertIn("oauth_nonce", parsed) + self.assertIn("oauth_signature", parsed) + + def test_oauth10a_redirect(self): + response = self.fetch("/oauth10a/client/login", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertTrue( + response.headers["Location"].endswith( + "/oauth1/server/authorize?oauth_token=zxcv" + ) + ) + # the cookie is base64('zxcv')|base64('1234') + self.assertTrue( + '_oauth_request_token="enhjdg==|MTIzNA=="' + in response.headers["Set-Cookie"], + response.headers["Set-Cookie"], + ) + + @unittest.skipIf(mock is None, "mock package not present") + def test_oauth10a_redirect_error(self): + with mock.patch.object(OAuth1ServerRequestTokenHandler, "get") as get: + get.side_effect = Exception("boom") + with ExpectLog(app_log, "Uncaught exception"): + response = self.fetch("/oauth10a/client/login", follow_redirects=False) + self.assertEqual(response.code, 500) + + def test_oauth10a_get_user(self): + response = self.fetch( + "/oauth10a/client/login?oauth_token=zxcv", + headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="}, + ) + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual(parsed["email"], "foo@example.com") + self.assertEqual(parsed["access_token"], dict(key="uiop", secret="5678")) + + def test_oauth10a_request_parameters(self): + response = self.fetch("/oauth10a/client/request_params") + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual(parsed["oauth_consumer_key"], "asdf") + self.assertEqual(parsed["oauth_token"], "uiop") + self.assertIn("oauth_nonce", parsed) + self.assertIn("oauth_signature", parsed) + + def test_oauth10a_get_user_coroutine_exception(self): + response = self.fetch( + "/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true", + headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="}, + ) + self.assertEqual(response.code, 503) + + def test_oauth2_redirect(self): + response = self.fetch("/oauth2/client/login", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertIn("/oauth2/server/authorize?", response.headers["Location"]) + + def test_facebook_login(self): + response = self.fetch("/facebook/client/login", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertTrue("/facebook/server/authorize?" in response.headers["Location"]) + response = self.fetch( + "/facebook/client/login?code=1234", follow_redirects=False + ) + self.assertEqual(response.code, 200) + user = json_decode(response.body) + self.assertEqual(user["access_token"], "asdf") + self.assertEqual(user["session_expires"], "3600") + + def base_twitter_redirect(self, url): + # Same as test_oauth10a_redirect + response = self.fetch(url, follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertTrue( + response.headers["Location"].endswith( + "/oauth1/server/authorize?oauth_token=zxcv" + ) + ) + # the cookie is base64('zxcv')|base64('1234') + self.assertIn( + '_oauth_request_token="enhjdg==|MTIzNA=="', + response.headers["Set-Cookie"], + response.headers["Set-Cookie"], + ) + + def test_twitter_redirect(self): + self.base_twitter_redirect("/twitter/client/login") + + def test_twitter_redirect_gen_coroutine(self): + self.base_twitter_redirect("/twitter/client/login_gen_coroutine") + + def test_twitter_authenticate_redirect(self): + response = self.fetch("/twitter/client/authenticate", follow_redirects=False) + self.assertEqual(response.code, 302) + self.assertTrue( + response.headers["Location"].endswith( + "/twitter/server/authenticate?oauth_token=zxcv" + ), + response.headers["Location"], + ) + # the cookie is base64('zxcv')|base64('1234') + self.assertIn( + '_oauth_request_token="enhjdg==|MTIzNA=="', + response.headers["Set-Cookie"], + response.headers["Set-Cookie"], + ) + + def test_twitter_get_user(self): + response = self.fetch( + "/twitter/client/login?oauth_token=zxcv", + headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="}, + ) + response.rethrow() + parsed = json_decode(response.body) + self.assertEqual( + parsed, + { + "access_token": { + "key": "hjkl", + "screen_name": "foo", + "secret": "vbnm", + }, + "name": "Foo", + "screen_name": "foo", + "username": "foo", + }, + ) + + def test_twitter_show_user(self): + response = self.fetch("/twitter/client/show_user?name=somebody") + response.rethrow() + self.assertEqual( + json_decode(response.body), {"name": "Somebody", "screen_name": "somebody"} + ) + + def test_twitter_show_user_error(self): + response = self.fetch("/twitter/client/show_user?name=error") + self.assertEqual(response.code, 500) + self.assertEqual(response.body, b"error from twitter request") + + +class GoogleLoginHandler(RequestHandler, GoogleOAuth2Mixin): + def initialize(self, test): + self.test = test + self._OAUTH_REDIRECT_URI = test.get_url("/client/login") + self._OAUTH_AUTHORIZE_URL = test.get_url("/google/oauth2/authorize") + self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/google/oauth2/token") + + @gen.coroutine + def get(self): + code = self.get_argument("code", None) + if code is not None: + # retrieve authenticate google user + access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI, code) + user = yield self.oauth2_request( + self.test.get_url("/google/oauth2/userinfo"), + access_token=access["access_token"], + ) + # return the user and access token as json + user["access_token"] = access["access_token"] + self.write(user) + else: + self.authorize_redirect( + redirect_uri=self._OAUTH_REDIRECT_URI, + client_id=self.settings["google_oauth"]["key"], + scope=["profile", "email"], + response_type="code", + extra_params={"prompt": "select_account"}, + ) + + +class GoogleOAuth2AuthorizeHandler(RequestHandler): + def get(self): + # issue a fake auth code and redirect to redirect_uri + code = "fake-authorization-code" + self.redirect(url_concat(self.get_argument("redirect_uri"), dict(code=code))) + + +class GoogleOAuth2TokenHandler(RequestHandler): + def post(self): + assert self.get_argument("code") == "fake-authorization-code" + # issue a fake token + self.finish( + {"access_token": "fake-access-token", "expires_in": "never-expires"} + ) + + +class GoogleOAuth2UserinfoHandler(RequestHandler): + def get(self): + assert self.get_argument("access_token") == "fake-access-token" + # return a fake user + self.finish({"name": "Foo", "email": "foo@example.com"}) + + +class GoogleOAuth2Test(AsyncHTTPTestCase): + def get_app(self): + return Application( + [ + # test endpoints + ("/client/login", GoogleLoginHandler, dict(test=self)), + # simulated google authorization server endpoints + ("/google/oauth2/authorize", GoogleOAuth2AuthorizeHandler), + ("/google/oauth2/token", GoogleOAuth2TokenHandler), + ("/google/oauth2/userinfo", GoogleOAuth2UserinfoHandler), + ], + google_oauth={ + "key": "fake_google_client_id", + "secret": "fake_google_client_secret", + }, + ) + + def test_google_login(self): + response = self.fetch("/client/login") + self.assertDictEqual( + { + "name": "Foo", + "email": "foo@example.com", + "access_token": "fake-access-token", + }, + json_decode(response.body), + ) diff --git a/python/user_packages/Python313/site-packages/tornado/test/autoreload_test.py b/python/user_packages/Python313/site-packages/tornado/test/autoreload_test.py new file mode 100644 index 0000000000000000000000000000000000000000..51bb52de20e3191abf6056367caf4074dbdd2db4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/autoreload_test.py @@ -0,0 +1,268 @@ +import os +import shutil +import subprocess +from subprocess import Popen +import sys +from tempfile import mkdtemp +import textwrap +import time +import unittest + + +class AutoreloadTest(unittest.TestCase): + def setUp(self): + # When these tests fail the output sometimes exceeds the default maxDiff. + self.maxDiff = 1024 + + self.path = mkdtemp() + + # Most test apps run themselves twice via autoreload. The first time it manually triggers + # a reload (could also do this by touching a file but this is faster since filesystem + # timestamps are not necessarily high resolution). The second time it exits directly + # so that the autoreload wrapper (if it is used) doesn't catch it. + # + # The last line of each such test's "main" program should be + # exec(open("run_twice_magic.py").read()) + self.write_files( + { + "run_twice_magic.py": """ + import os + import sys + + import tornado.autoreload + + sys.stdout.flush() + + if "TESTAPP_STARTED" not in os.environ: + os.environ["TESTAPP_STARTED"] = "1" + tornado.autoreload._reload() + else: + os._exit(0) + """ + } + ) + + def tearDown(self): + try: + shutil.rmtree(self.path) + except OSError: + # Windows disallows deleting files that are in use by + # another process, and even though we've waited for our + # child process below, it appears that its lock on these + # files is not guaranteed to be released by this point. + # Sleep and try again (once). + time.sleep(1) + shutil.rmtree(self.path) + + def write_files(self, tree, base_path=None): + """Write a directory tree to self.path. + + tree is a dictionary mapping file names to contents, or + sub-dictionaries representing subdirectories. + """ + if base_path is None: + base_path = self.path + for name, contents in tree.items(): + if isinstance(contents, dict): + os.mkdir(os.path.join(base_path, name)) + self.write_files(contents, os.path.join(base_path, name)) + else: + with open(os.path.join(base_path, name), "w", encoding="utf-8") as f: + f.write(textwrap.dedent(contents)) + + def run_subprocess(self, args): + # Make sure the tornado module under test is available to the test + # application + parts = [os.getcwd()] + if "PYTHONPATH" in os.environ: + parts += [ + os.path.join(os.getcwd(), part) + for part in os.environ["PYTHONPATH"].split(os.pathsep) + ] + pythonpath = os.pathsep.join(parts) + + p = Popen( + args, + stdout=subprocess.PIPE, + env=dict(os.environ, PYTHONPATH=pythonpath), + cwd=self.path, + universal_newlines=True, + encoding="utf-8", + ) + + # This timeout needs to be fairly generous for pypy due to jit + # warmup costs. + for i in range(40): + if p.poll() is not None: + break + time.sleep(0.1) + else: + p.kill() + raise Exception("subprocess failed to terminate") + + out = p.communicate()[0] + self.assertEqual(p.returncode, 0) + return out + + def test_reload(self): + main = """\ +import sys + +# In module mode, the path is set to the parent directory and we can import testapp. +try: + import testapp +except ImportError: + print("import testapp failed") +else: + print("import testapp succeeded") + +spec = getattr(sys.modules[__name__], '__spec__', None) +print(f"Starting {__name__=}, __spec__.name={getattr(spec, 'name', None)}") +exec(open("run_twice_magic.py", encoding="utf-8").read()) +""" + + # Create temporary test application + self.write_files( + { + "testapp": { + "__init__.py": "", + "__main__.py": main, + }, + } + ) + + # The autoreload wrapper should support all the same modes as the python interpreter. + # The wrapper itself should have no effect on this test so we try all modes with and + # without it. + for wrapper in [False, True]: + with self.subTest(wrapper=wrapper): + with self.subTest(mode="module"): + if wrapper: + base_args = [sys.executable, "-m", "tornado.autoreload"] + else: + base_args = [sys.executable] + # In module mode, the path is set to the parent directory and we can import + # testapp. Also, the __spec__.name is set to the fully qualified module name. + out = self.run_subprocess(base_args + ["-m", "testapp"]) + self.assertEqual( + out, + ( + "import testapp succeeded\n" + + "Starting __name__='__main__', __spec__.name=testapp.__main__\n" + ) + * 2, + ) + + with self.subTest(mode="file"): + out = self.run_subprocess(base_args + ["testapp/__main__.py"]) + # In file mode, we do not expect the path to be set so we can import testapp, + # but when the wrapper is used the -m argument to the python interpreter + # does this for us. + expect_import = ( + "import testapp succeeded" + if wrapper + else "import testapp failed" + ) + # In file mode there is no qualified module spec. + self.assertEqual( + out, + f"{expect_import}\nStarting __name__='__main__', __spec__.name=None\n" + * 2, + ) + + with self.subTest(mode="directory"): + # Running as a directory finds __main__.py like a module. It does not manipulate + # sys.path but it does set a spec with a name of exactly __main__. + out = self.run_subprocess(base_args + ["testapp"]) + expect_import = ( + "import testapp succeeded" + if wrapper + else "import testapp failed" + ) + self.assertEqual( + out, + f"{expect_import}\nStarting __name__='__main__', __spec__.name=__main__\n" + * 2, + ) + + def test_reload_wrapper_preservation(self): + # This test verifies that when `python -m tornado.autoreload` + # is used on an application that also has an internal + # autoreload, the reload wrapper is preserved on restart. + main = """\ +import sys + +# This import will fail if path is not set up correctly +import testapp + +if 'tornado.autoreload' not in sys.modules: + raise Exception('started without autoreload wrapper') + +print('Starting') +exec(open("run_twice_magic.py", encoding="utf-8").read()) +""" + + self.write_files( + { + "testapp": { + "__init__.py": "", + "__main__.py": main, + }, + } + ) + + out = self.run_subprocess( + [sys.executable, "-m", "tornado.autoreload", "-m", "testapp"] + ) + self.assertEqual(out, "Starting\n" * 2) + + def test_reload_wrapper_args(self): + main = """\ +import os +import sys + +print(os.path.basename(sys.argv[0])) +print(f'argv={sys.argv[1:]}') +exec(open("run_twice_magic.py", encoding="utf-8").read()) +""" + # Create temporary test application + self.write_files({"main.py": main}) + + # Make sure the tornado module under test is available to the test + # application + out = self.run_subprocess( + [ + sys.executable, + "-m", + "tornado.autoreload", + "main.py", + "arg1", + "--arg2", + "-m", + "arg3", + ], + ) + + self.assertEqual(out, "main.py\nargv=['arg1', '--arg2', '-m', 'arg3']\n" * 2) + + def test_reload_wrapper_until_success(self): + main = """\ +import os +import sys + +if "TESTAPP_STARTED" in os.environ: + print("exiting cleanly") + sys.exit(0) +else: + print("reloading") + exec(open("run_twice_magic.py", encoding="utf-8").read()) +""" + + # Create temporary test application + self.write_files({"main.py": main}) + + out = self.run_subprocess( + [sys.executable, "-m", "tornado.autoreload", "--until-success", "main.py"] + ) + + self.assertEqual(out, "reloading\nexiting cleanly\n") diff --git a/python/user_packages/Python313/site-packages/tornado/test/circlerefs_test.py b/python/user_packages/Python313/site-packages/tornado/test/circlerefs_test.py new file mode 100644 index 0000000000000000000000000000000000000000..326636edcb510dc526005c8ea5fadf2759754224 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/circlerefs_test.py @@ -0,0 +1,217 @@ +"""Test script to find circular references. + +Circular references are not leaks per se, because they will eventually +be GC'd. However, on CPython, they prevent the reference-counting fast +path from being used and instead rely on the slower full GC. This +increases memory footprint and CPU overhead, so we try to eliminate +circular references created by normal operation. +""" + +import asyncio +import contextlib +import gc +import io +import sys +import traceback +import types +import typing +import unittest + +import tornado +from tornado import web, gen, httpclient +from tornado.test.util import skipNotCPython + + +def find_circular_references(garbage): + """Find circular references in a list of objects. + + The garbage list contains objects that participate in a cycle, + but also the larger set of objects kept alive by that cycle. + This function finds subsets of those objects that make up + the cycle(s). + """ + + def inner(level): + for item in level: + item_id = id(item) + if item_id not in garbage_ids: + continue + if item_id in visited_ids: + continue + if item_id in stack_ids: + candidate = stack[stack.index(item) :] + candidate.append(item) + found.append(candidate) + continue + + stack.append(item) + stack_ids.add(item_id) + inner(gc.get_referents(item)) + stack.pop() + stack_ids.remove(item_id) + visited_ids.add(item_id) + + found: typing.List[object] = [] + stack = [] + stack_ids = set() + garbage_ids = set(map(id, garbage)) + visited_ids = set() + + inner(garbage) + return found + + +@contextlib.contextmanager +def assert_no_cycle_garbage(): + """Raise AssertionError if the wrapped code creates garbage with cycles.""" + gc.disable() + gc.collect() + gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_SAVEALL) + yield + try: + # We have DEBUG_STATS on which causes gc.collect to write to stderr. + # Capture the output instead of spamming the logs on passing runs. + f = io.StringIO() + old_stderr = sys.stderr + sys.stderr = f + try: + gc.collect() + finally: + sys.stderr = old_stderr + garbage = gc.garbage[:] + # Must clear gc.garbage (the same object, not just replacing it with a + # new list) to avoid warnings at shutdown. + gc.garbage[:] = [] + if len(garbage) == 0: + return + for circular in find_circular_references(garbage): + f.write("\n==========\n Circular \n==========") + for item in circular: + f.write(f"\n {repr(item)}") + for item in circular: + if isinstance(item, types.FrameType): + f.write(f"\nLocals: {item.f_locals}") + f.write(f"\nTraceback: {repr(item)}") + traceback.print_stack(item) + del garbage + raise AssertionError(f.getvalue()) + finally: + gc.set_debug(0) + gc.enable() + + +# GC behavior is cpython-specific +@skipNotCPython +class CircleRefsTest(unittest.TestCase): + def test_known_leak(self): + # Construct a known leak scenario to make sure the test harness works. + class C: + def __init__(self, name): + self.name = name + self.a: typing.Optional[C] = None + self.b: typing.Optional[C] = None + self.c: typing.Optional[C] = None + + def __repr__(self): + return f"name={self.name}" + + with self.assertRaises(AssertionError) as cm: + with assert_no_cycle_garbage(): + # a and b form a reference cycle. c is not part of the cycle, + # but it cannot be GC'd while a and b are alive. + a = C("a") + b = C("b") + c = C("c") + a.b = b + a.c = c + b.a = a + b.c = c + del a, b + self.assertIn("Circular", str(cm.exception)) + # Leading spaces ensure we only catch these at the beginning of a line, meaning they are a + # cycle participant and not simply the contents of a locals dict or similar container. (This + # depends on the formatting above which isn't ideal but this test evolved from a + # command-line script) Note that the behavior here changed in python 3.11; in newer pythons + # locals are handled a bit differently and the test passes without the spaces. + self.assertIn(" name=a", str(cm.exception)) + self.assertIn(" name=b", str(cm.exception)) + self.assertNotIn(" name=c", str(cm.exception)) + + async def run_handler(self, handler_class): + app = web.Application( + [ + (r"/", handler_class), + ] + ) + socket, port = tornado.testing.bind_unused_port() + server = tornado.httpserver.HTTPServer(app) + server.add_socket(socket) + + client = httpclient.AsyncHTTPClient() + with assert_no_cycle_garbage(): + # Only the fetch (and the corresponding server-side handler) + # are being tested for cycles. In particular, the Application + # object has internal cycles (as of this writing) which we don't + # care to fix since in real world usage the Application object + # is effectively a global singleton. + await client.fetch(f"http://127.0.0.1:{port}/") + client.close() + server.stop() + socket.close() + + def test_sync_handler(self): + class Handler(web.RequestHandler): + def get(self): + self.write("ok\n") + + asyncio.run(self.run_handler(Handler)) + + def test_finish_exception_handler(self): + class Handler(web.RequestHandler): + def get(self): + raise web.Finish("ok\n") + + asyncio.run(self.run_handler(Handler)) + + def test_coro_handler(self): + class Handler(web.RequestHandler): + @gen.coroutine + def get(self): + yield asyncio.sleep(0.01) + self.write("ok\n") + + asyncio.run(self.run_handler(Handler)) + + def test_async_handler(self): + class Handler(web.RequestHandler): + async def get(self): + await asyncio.sleep(0.01) + self.write("ok\n") + + asyncio.run(self.run_handler(Handler)) + + def test_run_on_executor(self): + # From https://github.com/tornadoweb/tornado/issues/2620 + # + # When this test was introduced it found cycles in IOLoop.add_future + # and tornado.concurrent.chain_future. + import concurrent.futures + + with concurrent.futures.ThreadPoolExecutor(1) as thread_pool: + + class Factory: + executor = thread_pool + + @tornado.concurrent.run_on_executor + def run(self): + return None + + factory = Factory() + + async def main(): + # The cycle is not reported on the first call. It's not clear why. + for i in range(2): + await factory.run() + + with assert_no_cycle_garbage(): + asyncio.run(main()) diff --git a/python/user_packages/Python313/site-packages/tornado/test/concurrent_test.py b/python/user_packages/Python313/site-packages/tornado/test/concurrent_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fc19e4027b71e2722274cc511ce58f2c52580128 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/concurrent_test.py @@ -0,0 +1,231 @@ +# +# Copyright 2012 Facebook +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +from concurrent import futures +import logging +import re +import socket +import unittest + +from tornado.concurrent import ( + Future, + chain_future, + run_on_executor, + future_set_result_unless_cancelled, +) +from tornado.escape import utf8, to_unicode +from tornado import gen +from tornado.iostream import IOStream +from tornado.tcpserver import TCPServer +from tornado.testing import AsyncTestCase, bind_unused_port, gen_test + + +class MiscFutureTest(AsyncTestCase): + def test_future_set_result_unless_cancelled(self): + fut = Future() # type: Future[int] + future_set_result_unless_cancelled(fut, 42) + self.assertEqual(fut.result(), 42) + self.assertFalse(fut.cancelled()) + + fut = Future() + fut.cancel() + is_cancelled = fut.cancelled() + future_set_result_unless_cancelled(fut, 42) + self.assertEqual(fut.cancelled(), is_cancelled) + if not is_cancelled: + self.assertEqual(fut.result(), 42) + + +class ChainFutureTest(AsyncTestCase): + @gen_test + async def test_asyncio_futures(self): + fut: Future[int] = Future() + fut2: Future[int] = Future() + chain_future(fut, fut2) + fut.set_result(42) + result = await fut2 + self.assertEqual(result, 42) + + @gen_test + async def test_concurrent_futures(self): + # A three-step chain: two concurrent futures (showing that both arguments to chain_future + # can be concurrent futures), and then one from a concurrent future to an asyncio future so + # we can use it in await. + fut: futures.Future[int] = futures.Future() + fut2: futures.Future[int] = futures.Future() + fut3: Future[int] = Future() + chain_future(fut, fut2) + chain_future(fut2, fut3) + fut.set_result(42) + result = await fut3 + self.assertEqual(result, 42) + + +# The following series of classes demonstrate and test various styles +# of use, with and without generators and futures. + + +class CapServer(TCPServer): + @gen.coroutine + def handle_stream(self, stream, address): + data = yield stream.read_until(b"\n") + data = to_unicode(data) + if data == data.upper(): + stream.write(b"error\talready capitalized\n") + else: + # data already has \n + stream.write(utf8("ok\t%s" % data.upper())) + stream.close() + + +class CapError(Exception): + pass + + +class BaseCapClient: + def __init__(self, port): + self.port = port + + def process_response(self, data): + m = re.match("(.*)\t(.*)\n", to_unicode(data)) + if m is None: + raise Exception("did not match") + status, message = m.groups() + if status == "ok": + return message + else: + raise CapError(message) + + +class GeneratorCapClient(BaseCapClient): + @gen.coroutine + def capitalize(self, request_data): + logging.debug("capitalize") + stream = IOStream(socket.socket()) + logging.debug("connecting") + yield stream.connect(("127.0.0.1", self.port)) + stream.write(utf8(request_data + "\n")) + logging.debug("reading") + data = yield stream.read_until(b"\n") + logging.debug("returning") + stream.close() + raise gen.Return(self.process_response(data)) + + +class GeneratorCapClientTest(AsyncTestCase): + def setUp(self): + super().setUp() + self.server = CapServer() + sock, port = bind_unused_port() + self.server.add_sockets([sock]) + self.client = GeneratorCapClient(port=port) + + def tearDown(self): + self.server.stop() + super().tearDown() + + def test_future(self): + future = self.client.capitalize("hello") + self.io_loop.add_future(future, self.stop) + self.wait() + self.assertEqual(future.result(), "HELLO") + + def test_future_error(self): + future = self.client.capitalize("HELLO") + self.io_loop.add_future(future, self.stop) + self.wait() + self.assertRaisesRegex(CapError, "already capitalized", future.result) + + def test_generator(self): + @gen.coroutine + def f(): + result = yield self.client.capitalize("hello") + self.assertEqual(result, "HELLO") + + self.io_loop.run_sync(f) + + def test_generator_error(self): + @gen.coroutine + def f(): + with self.assertRaisesRegex(CapError, "already capitalized"): + yield self.client.capitalize("HELLO") + + self.io_loop.run_sync(f) + + +class RunOnExecutorTest(AsyncTestCase): + @gen_test + def test_no_calling(self): + class Object: + def __init__(self): + self.executor = futures.thread.ThreadPoolExecutor(1) + + @run_on_executor + def f(self): + return 42 + + o = Object() + answer = yield o.f() + self.assertEqual(answer, 42) + + @gen_test + def test_call_with_no_args(self): + class Object: + def __init__(self): + self.executor = futures.thread.ThreadPoolExecutor(1) + + @run_on_executor() + def f(self): + return 42 + + o = Object() + answer = yield o.f() + self.assertEqual(answer, 42) + + @gen_test + def test_call_with_executor(self): + class Object: + def __init__(self): + self.__executor = futures.thread.ThreadPoolExecutor(1) + + @run_on_executor(executor="_Object__executor") + def f(self): + return 42 + + o = Object() + answer = yield o.f() + self.assertEqual(answer, 42) + + @gen_test + def test_async_await(self): + class Object: + def __init__(self): + self.executor = futures.thread.ThreadPoolExecutor(1) + + @run_on_executor() + def f(self): + return 42 + + o = Object() + + async def f(): + answer = await o.f() + return answer + + result = yield f() + self.assertEqual(result, 42) + + +if __name__ == "__main__": + unittest.main() diff --git a/python/user_packages/Python313/site-packages/tornado/test/csv_translations/fr_FR.csv b/python/user_packages/Python313/site-packages/tornado/test/csv_translations/fr_FR.csv new file mode 100644 index 0000000000000000000000000000000000000000..ad092cc5638a05981091540e6d55f58990d7322f --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/csv_translations/fr_FR.csv @@ -0,0 +1 @@ +"school","école" diff --git a/python/user_packages/Python313/site-packages/tornado/test/curl_httpclient_test.py b/python/user_packages/Python313/site-packages/tornado/test/curl_httpclient_test.py new file mode 100644 index 0000000000000000000000000000000000000000..795bf3d1a55bc0d55fe96cb5f4977da168eedecb --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/curl_httpclient_test.py @@ -0,0 +1,125 @@ +from hashlib import md5 +import unittest + +from tornado.escape import utf8 +from tornado.testing import AsyncHTTPTestCase +from tornado.test import httpclient_test +from tornado.web import Application, RequestHandler + + +try: + import pycurl +except ImportError: + pycurl = None # type: ignore + +if pycurl is not None: + from tornado.curl_httpclient import CurlAsyncHTTPClient + + +@unittest.skipIf(pycurl is None, "pycurl module not present") +class CurlHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase): + def get_http_client(self): + client = CurlAsyncHTTPClient(defaults=dict(allow_ipv6=False)) + # make sure AsyncHTTPClient magic doesn't give us the wrong class + self.assertTrue(isinstance(client, CurlAsyncHTTPClient)) + return client + + +class DigestAuthHandler(RequestHandler): + def initialize(self, username, password): + self.username = username + self.password = password + + def get(self): + realm = "test" + opaque = "asdf" + # Real implementations would use a random nonce. + nonce = "1234" + + auth_header = self.request.headers.get("Authorization", None) + if auth_header is not None: + auth_mode, params = auth_header.split(" ", 1) + assert auth_mode == "Digest" + param_dict = {} + for pair in params.split(","): + k, v = pair.strip().split("=", 1) + if v[0] == '"' and v[-1] == '"': + v = v[1:-1] + param_dict[k] = v + assert param_dict["realm"] == realm + assert param_dict["opaque"] == opaque + assert param_dict["nonce"] == nonce + assert param_dict["username"] == self.username + assert param_dict["uri"] == self.request.path + h1 = md5(utf8(f"{self.username}:{realm}:{self.password}")).hexdigest() + h2 = md5(utf8(f"{self.request.method}:{self.request.path}")).hexdigest() + digest = md5(utf8(f"{h1}:{nonce}:{h2}")).hexdigest() + if digest == param_dict["response"]: + self.write("ok") + else: + self.write("fail") + else: + self.set_status(401) + self.set_header( + "WWW-Authenticate", + f'Digest realm="{realm}", nonce="{nonce}", opaque="{opaque}"', + ) + + +class CustomReasonHandler(RequestHandler): + def get(self): + self.set_status(200, "Custom reason") + + +class CustomFailReasonHandler(RequestHandler): + def get(self): + self.set_status(400, "Custom reason") + + +@unittest.skipIf(pycurl is None, "pycurl module not present") +class CurlHTTPClientTestCase(AsyncHTTPTestCase): + def setUp(self): + super().setUp() + self.http_client = self.create_client() + + def get_app(self): + return Application( + [ + ("/digest", DigestAuthHandler, {"username": "foo", "password": "bar"}), + ( + "/digest_non_ascii", + DigestAuthHandler, + {"username": "foo", "password": "barユ£"}, + ), + ("/custom_reason", CustomReasonHandler), + ("/custom_fail_reason", CustomFailReasonHandler), + ] + ) + + def create_client(self, **kwargs): + return CurlAsyncHTTPClient( + force_instance=True, defaults=dict(allow_ipv6=False), **kwargs + ) + + def test_digest_auth(self): + response = self.fetch( + "/digest", auth_mode="digest", auth_username="foo", auth_password="bar" + ) + self.assertEqual(response.body, b"ok") + + def test_custom_reason(self): + response = self.fetch("/custom_reason") + self.assertEqual(response.reason, "Custom reason") + + def test_fail_custom_reason(self): + response = self.fetch("/custom_fail_reason") + self.assertEqual(str(response.error), "HTTP 400: Custom reason") + + def test_digest_auth_non_ascii(self): + response = self.fetch( + "/digest_non_ascii", + auth_mode="digest", + auth_username="foo", + auth_password="barユ£", + ) + self.assertEqual(response.body, b"ok") diff --git a/python/user_packages/Python313/site-packages/tornado/test/escape_test.py b/python/user_packages/Python313/site-packages/tornado/test/escape_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3753d40ee25de8443a4f97ca858682ad42cbe071 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/escape_test.py @@ -0,0 +1,324 @@ +import unittest + +import tornado +from tornado.escape import ( + utf8, + xhtml_escape, + xhtml_unescape, + url_escape, + url_unescape, + to_unicode, + json_decode, + json_encode, + squeeze, + recursive_unicode, +) +from tornado.util import unicode_type + +from typing import List, Tuple, Union, Dict, Any # noqa: F401 + +linkify_tests = [ + # (input, linkify_kwargs, expected_output) + ( + "hello http://world.com/!", + {}, + 'hello http://world.com/!', + ), + ( + "hello http://world.com/with?param=true&stuff=yes", + {}, + 'hello http://world.com/with?param=true&stuff=yes', # noqa: E501 + ), + # an opened paren followed by many chars killed Gruber's regex + ( + "http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + {}, + 'http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', # noqa: E501 + ), + # as did too many dots at the end + ( + "http://url.com/withmany.......................................", + {}, + 'http://url.com/withmany.......................................', # noqa: E501 + ), + ( + "http://url.com/withmany((((((((((((((((((((((((((((((((((a)", + {}, + 'http://url.com/withmany((((((((((((((((((((((((((((((((((a)', # noqa: E501 + ), + # some examples from http://daringfireball.net/2009/11/liberal_regex_for_matching_urls + # plus a fex extras (such as multiple parentheses). + ( + "http://foo.com/blah_blah", + {}, + 'http://foo.com/blah_blah', + ), + ( + "http://foo.com/blah_blah/", + {}, + 'http://foo.com/blah_blah/', + ), + ( + "(Something like http://foo.com/blah_blah)", + {}, + '(Something like http://foo.com/blah_blah)', + ), + ( + "http://foo.com/blah_blah_(wikipedia)", + {}, + 'http://foo.com/blah_blah_(wikipedia)', + ), + ( + "http://foo.com/blah_(blah)_(wikipedia)_blah", + {}, + 'http://foo.com/blah_(blah)_(wikipedia)_blah', # noqa: E501 + ), + ( + "(Something like http://foo.com/blah_blah_(wikipedia))", + {}, + '(Something like http://foo.com/blah_blah_(wikipedia))', # noqa: E501 + ), + ( + "http://foo.com/blah_blah.", + {}, + 'http://foo.com/blah_blah.', + ), + ( + "http://foo.com/blah_blah/.", + {}, + 'http://foo.com/blah_blah/.', + ), + ( + "", + {}, + '<http://foo.com/blah_blah>', + ), + ( + "", + {}, + '<http://foo.com/blah_blah/>', + ), + ( + "http://foo.com/blah_blah,", + {}, + 'http://foo.com/blah_blah,', + ), + ( + "http://www.example.com/wpstyle/?p=364.", + {}, + 'http://www.example.com/wpstyle/?p=364.', # noqa: E501 + ), + ( + "rdar://1234", + {"permitted_protocols": ["http", "rdar"]}, + 'rdar://1234', + ), + ( + "rdar:/1234", + {"permitted_protocols": ["rdar"]}, + 'rdar:/1234', + ), + ( + "http://userid:password@example.com:8080", + {}, + 'http://userid:password@example.com:8080', # noqa: E501 + ), + ( + "http://userid@example.com", + {}, + 'http://userid@example.com', + ), + ( + "http://userid@example.com:8080", + {}, + 'http://userid@example.com:8080', + ), + ( + "http://userid:password@example.com", + {}, + 'http://userid:password@example.com', + ), + ( + "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e", + {"permitted_protocols": ["http", "message"]}, + '' + "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e", + ), + ( + "http://\u27a1.ws/\u4a39", + {}, + 'http://\u27a1.ws/\u4a39', + ), + ( + "http://example.com", + {}, + '<tag>http://example.com</tag>', + ), + ( + "Just a www.example.com link.", + {}, + 'Just a www.example.com link.', + ), + ( + "Just a www.example.com link.", + {"require_protocol": True}, + "Just a www.example.com link.", + ), + ( + "A http://reallylong.com/link/that/exceedsthelenglimit.html", + {"require_protocol": True, "shorten": True}, + 'A http://reallylong.com/link...', # noqa: E501 + ), + ( + "A http://reallylongdomainnamethatwillbetoolong.com/hi!", + {"shorten": True}, + 'A http://reallylongdomainnametha...!', # noqa: E501 + ), + ( + "A file:///passwords.txt and http://web.com link", + {}, + 'A file:///passwords.txt and http://web.com link', + ), + ( + "A file:///passwords.txt and http://web.com link", + {"permitted_protocols": ["file"]}, + 'A file:///passwords.txt and http://web.com link', + ), + ( + "www.external-link.com", + {"extra_params": 'rel="nofollow" class="external"'}, + 'www.external-link.com', # noqa: E501 + ), + ( + "www.external-link.com and www.internal-link.com/blogs extra", + { + "extra_params": lambda href: ( + 'class="internal"' + if href.startswith("http://www.internal-link.com") + else 'rel="nofollow" class="external"' + ) + }, + 'www.external-link.com' # noqa: E501 + ' and www.internal-link.com/blogs extra', # noqa: E501 + ), + ( + "www.external-link.com", + {"extra_params": lambda href: ' rel="nofollow" class="external" '}, + 'www.external-link.com', # noqa: E501 + ), +] # type: List[Tuple[Union[str, bytes], Dict[str, Any], str]] + + +class EscapeTestCase(unittest.TestCase): + def test_linkify(self): + for text, kwargs, html in linkify_tests: + linked = tornado.escape.linkify(text, **kwargs) + self.assertEqual(linked, html) + + def test_xhtml_escape(self): + tests = [ + ("", "<foo>"), + ("", "<foo>"), + (b"", b"<foo>"), + ("<>&\"'", "<>&"'"), + ("&", "&amp;"), + ("<\u00e9>", "<\u00e9>"), + (b"<\xc3\xa9>", b"<\xc3\xa9>"), + ] # type: List[Tuple[Union[str, bytes], Union[str, bytes]]] + for unescaped, escaped in tests: + self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped)) + self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped))) + + def test_xhtml_unescape_numeric(self): + tests = [ + ("foo bar", "foo bar"), + ("foo bar", "foo bar"), + ("foo bar", "foo bar"), + ("foo઼bar", "foo\u0abcbar"), + ("foo&#xyz;bar", "foo&#xyz;bar"), # invalid encoding + ("foo&#;bar", "foo&#;bar"), # invalid encoding + ("foo&#x;bar", "foo&#x;bar"), # invalid encoding + ] + for escaped, unescaped in tests: + self.assertEqual(unescaped, xhtml_unescape(escaped)) + + def test_url_escape_unicode(self): + tests = [ + # byte strings are passed through as-is + ("\u00e9".encode(), "%C3%A9"), + ("\u00e9".encode("latin1"), "%E9"), + # unicode strings become utf8 + ("\u00e9", "%C3%A9"), + ] # type: List[Tuple[Union[str, bytes], str]] + for unescaped, escaped in tests: + self.assertEqual(url_escape(unescaped), escaped) + + def test_url_unescape_unicode(self): + tests = [ + ("%C3%A9", "\u00e9", "utf8"), + ("%C3%A9", "\u00c3\u00a9", "latin1"), + ("%C3%A9", utf8("\u00e9"), None), + ] + for escaped, unescaped, encoding in tests: + # input strings to url_unescape should only contain ascii + # characters, but make sure the function accepts both byte + # and unicode strings. + self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped) + self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped) + + def test_url_escape_quote_plus(self): + unescaped = "+ #%" + plus_escaped = "%2B+%23%25" + escaped = "%2B%20%23%25" + self.assertEqual(url_escape(unescaped), plus_escaped) + self.assertEqual(url_escape(unescaped, plus=False), escaped) + self.assertEqual(url_unescape(plus_escaped), unescaped) + self.assertEqual(url_unescape(escaped, plus=False), unescaped) + self.assertEqual(url_unescape(plus_escaped, encoding=None), utf8(unescaped)) + self.assertEqual( + url_unescape(escaped, encoding=None, plus=False), utf8(unescaped) + ) + + def test_escape_return_types(self): + # On python2 the escape methods should generally return the same + # type as their argument + self.assertEqual(type(xhtml_escape("foo")), str) + self.assertEqual(type(xhtml_escape("foo")), unicode_type) + + def test_json_decode(self): + # json_decode accepts both bytes and unicode, but strings it returns + # are always unicode. + self.assertEqual(json_decode(b'"foo"'), "foo") + self.assertEqual(json_decode('"foo"'), "foo") + + # Non-ascii bytes are interpreted as utf8 + self.assertEqual(json_decode(utf8('"\u00e9"')), "\u00e9") + + def test_json_encode(self): + # json deals with strings, not bytes. On python 2 byte strings will + # convert automatically if they are utf8; on python 3 byte strings + # are not allowed. + self.assertEqual(json_decode(json_encode("\u00e9")), "\u00e9") + if bytes is str: + self.assertEqual(json_decode(json_encode(utf8("\u00e9"))), "\u00e9") + self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9") + + def test_squeeze(self): + self.assertEqual( + squeeze("sequences of whitespace chars"), + "sequences of whitespace chars", + ) + + def test_recursive_unicode(self): + tests = { + "dict": {b"foo": b"bar"}, + "list": [b"foo", b"bar"], + "tuple": (b"foo", b"bar"), + "bytes": b"foo", + } + self.assertEqual(recursive_unicode(tests["dict"]), {"foo": "bar"}) + self.assertEqual(recursive_unicode(tests["list"]), ["foo", "bar"]) + self.assertEqual(recursive_unicode(tests["tuple"]), ("foo", "bar")) + self.assertEqual(recursive_unicode(tests["bytes"]), "foo") diff --git a/python/user_packages/Python313/site-packages/tornado/test/gen_test.py b/python/user_packages/Python313/site-packages/tornado/test/gen_test.py new file mode 100644 index 0000000000000000000000000000000000000000..439d73295f92c03a816780dc1e7893e7716a162d --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/gen_test.py @@ -0,0 +1,1123 @@ +import asyncio +from concurrent import futures +import gc +import datetime +import platform +import sys +import time +import weakref +import unittest + +from tornado.concurrent import Future +from tornado.log import app_log +from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test +from tornado.test.util import skipNotCPython +from tornado.web import Application, RequestHandler, HTTPError + +from tornado import gen + +try: + import contextvars +except ImportError: + contextvars = None # type: ignore + +import typing + +if typing.TYPE_CHECKING: + from typing import List, Optional # noqa: F401 + + +class GenBasicTest(AsyncTestCase): + @gen.coroutine + def delay(self, iterations, arg): + """Returns arg after a number of IOLoop iterations.""" + for i in range(iterations): + yield gen.moment + raise gen.Return(arg) + + @gen.coroutine + def async_future(self, result): + yield gen.moment + return result + + @gen.coroutine + def async_exception(self, e): + yield gen.moment + raise e + + @gen.coroutine + def add_one_async(self, x): + yield gen.moment + raise gen.Return(x + 1) + + def test_no_yield(self): + @gen.coroutine + def f(): + pass + + self.io_loop.run_sync(f) + + def test_exception_phase1(self): + @gen.coroutine + def f(): + 1 / 0 + + self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f) + + def test_exception_phase2(self): + @gen.coroutine + def f(): + yield gen.moment + 1 / 0 + + self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f) + + def test_bogus_yield(self): + @gen.coroutine + def f(): + yield 42 + + self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f) + + def test_bogus_yield_tuple(self): + @gen.coroutine + def f(): + yield (1, 2) + + self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f) + + def test_reuse(self): + @gen.coroutine + def f(): + yield gen.moment + + self.io_loop.run_sync(f) + self.io_loop.run_sync(f) + + def test_none(self): + @gen.coroutine + def f(): + yield None + + self.io_loop.run_sync(f) + + def test_multi(self): + @gen.coroutine + def f(): + results = yield [self.add_one_async(1), self.add_one_async(2)] + self.assertEqual(results, [2, 3]) + + self.io_loop.run_sync(f) + + def test_multi_dict(self): + @gen.coroutine + def f(): + results = yield dict(foo=self.add_one_async(1), bar=self.add_one_async(2)) + self.assertEqual(results, dict(foo=2, bar=3)) + + self.io_loop.run_sync(f) + + def test_multi_delayed(self): + @gen.coroutine + def f(): + # callbacks run at different times + responses = yield gen.multi_future( + [self.delay(3, "v1"), self.delay(1, "v2")] + ) + self.assertEqual(responses, ["v1", "v2"]) + + self.io_loop.run_sync(f) + + def test_multi_dict_delayed(self): + @gen.coroutine + def f(): + # callbacks run at different times + responses = yield gen.multi_future( + dict(foo=self.delay(3, "v1"), bar=self.delay(1, "v2")) + ) + self.assertEqual(responses, dict(foo="v1", bar="v2")) + + self.io_loop.run_sync(f) + + @gen_test + def test_multi_performance(self): + # Yielding a list used to have quadratic performance; make + # sure a large list stays reasonable. On my laptop a list of + # 2000 used to take 1.8s, now it takes 0.12. + start = time.time() + yield [gen.moment for i in range(2000)] + end = time.time() + self.assertLess(end - start, 1.0) + + @gen_test + def test_multi_empty(self): + # Empty lists or dicts should return the same type. + x = yield [] + self.assertTrue(isinstance(x, list)) + y = yield {} + self.assertTrue(isinstance(y, dict)) + + @gen_test + def test_future(self): + result = yield self.async_future(1) + self.assertEqual(result, 1) + + @gen_test + def test_multi_future(self): + results = yield [self.async_future(1), self.async_future(2)] + self.assertEqual(results, [1, 2]) + + @gen_test + def test_multi_future_duplicate(self): + # Note that this doesn't work with native corotines, only with + # decorated coroutines. + f = self.async_future(2) + results = yield [self.async_future(1), f, self.async_future(3), f] + self.assertEqual(results, [1, 2, 3, 2]) + + @gen_test + def test_multi_dict_future(self): + results = yield dict(foo=self.async_future(1), bar=self.async_future(2)) + self.assertEqual(results, dict(foo=1, bar=2)) + + @gen_test + def test_multi_exceptions(self): + with ExpectLog(app_log, "Multiple exceptions in yield list"): + with self.assertRaises(RuntimeError) as cm: + yield gen.Multi( + [ + self.async_exception(RuntimeError("error 1")), + self.async_exception(RuntimeError("error 2")), + ] + ) + self.assertEqual(str(cm.exception), "error 1") + + # With only one exception, no error is logged. + with self.assertRaises(RuntimeError): + yield gen.Multi( + [self.async_exception(RuntimeError("error 1")), self.async_future(2)] + ) + + # Exception logging may be explicitly quieted. + with self.assertRaises(RuntimeError): + yield gen.Multi( + [ + self.async_exception(RuntimeError("error 1")), + self.async_exception(RuntimeError("error 2")), + ], + quiet_exceptions=RuntimeError, + ) + + @gen_test + def test_multi_future_exceptions(self): + with ExpectLog(app_log, "Multiple exceptions in yield list"): + with self.assertRaises(RuntimeError) as cm: + yield [ + self.async_exception(RuntimeError("error 1")), + self.async_exception(RuntimeError("error 2")), + ] + self.assertEqual(str(cm.exception), "error 1") + + # With only one exception, no error is logged. + with self.assertRaises(RuntimeError): + yield [self.async_exception(RuntimeError("error 1")), self.async_future(2)] + + # Exception logging may be explicitly quieted. + with self.assertRaises(RuntimeError): + yield gen.multi_future( + [ + self.async_exception(RuntimeError("error 1")), + self.async_exception(RuntimeError("error 2")), + ], + quiet_exceptions=RuntimeError, + ) + + def test_sync_raise_return(self): + @gen.coroutine + def f(): + raise gen.Return() + + self.io_loop.run_sync(f) + + def test_async_raise_return(self): + @gen.coroutine + def f(): + yield gen.moment + raise gen.Return() + + self.io_loop.run_sync(f) + + def test_sync_raise_return_value(self): + @gen.coroutine + def f(): + raise gen.Return(42) + + self.assertEqual(42, self.io_loop.run_sync(f)) + + def test_sync_raise_return_value_tuple(self): + @gen.coroutine + def f(): + raise gen.Return((1, 2)) + + self.assertEqual((1, 2), self.io_loop.run_sync(f)) + + def test_async_raise_return_value(self): + @gen.coroutine + def f(): + yield gen.moment + raise gen.Return(42) + + self.assertEqual(42, self.io_loop.run_sync(f)) + + def test_async_raise_return_value_tuple(self): + @gen.coroutine + def f(): + yield gen.moment + raise gen.Return((1, 2)) + + self.assertEqual((1, 2), self.io_loop.run_sync(f)) + + +class GenCoroutineTest(AsyncTestCase): + def setUp(self): + # Stray StopIteration exceptions can lead to tests exiting prematurely, + # so we need explicit checks here to make sure the tests run all + # the way through. + self.finished = False + super().setUp() + + def tearDown(self): + super().tearDown() + assert self.finished + + def test_attributes(self): + self.finished = True + + def f(): + yield gen.moment + + coro = gen.coroutine(f) + self.assertEqual(coro.__name__, f.__name__) + self.assertEqual(coro.__module__, f.__module__) + self.assertIs(coro.__wrapped__, f) # type: ignore + + def test_is_coroutine_function(self): + self.finished = True + + def f(): + yield gen.moment + + coro = gen.coroutine(f) + self.assertFalse(gen.is_coroutine_function(f)) + self.assertTrue(gen.is_coroutine_function(coro)) + self.assertFalse(gen.is_coroutine_function(coro())) + + @gen_test + def test_sync_gen_return(self): + @gen.coroutine + def f(): + raise gen.Return(42) + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_async_gen_return(self): + @gen.coroutine + def f(): + yield gen.moment + raise gen.Return(42) + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_sync_return(self): + @gen.coroutine + def f(): + return 42 + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_async_return(self): + @gen.coroutine + def f(): + yield gen.moment + return 42 + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_async_early_return(self): + # A yield statement exists but is not executed, which means + # this function "returns" via an exception. This exception + # doesn't happen before the exception handling is set up. + @gen.coroutine + def f(): + if True: + return 42 + yield gen.Task(self.io_loop.add_callback) + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_async_await(self): + @gen.coroutine + def f1(): + yield gen.moment + raise gen.Return(42) + + # This test verifies that an async function can await a + # yield-based gen.coroutine, and that a gen.coroutine + # (the test method itself) can yield an async function. + async def f2(): + result = await f1() + return result + + result = yield f2() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_asyncio_sleep_zero(self): + # asyncio.sleep(0) turns into a special case (equivalent to + # `yield None`) + async def f(): + import asyncio + + await asyncio.sleep(0) + return 42 + + result = yield f() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_async_await_mixed_multi_native_future(self): + @gen.coroutine + def f1(): + yield gen.moment + + async def f2(): + await f1() + return 42 + + @gen.coroutine + def f3(): + yield gen.moment + raise gen.Return(43) + + results = yield [f2(), f3()] + self.assertEqual(results, [42, 43]) + self.finished = True + + @gen_test + def test_async_with_timeout(self): + async def f1(): + return 42 + + result = yield gen.with_timeout(datetime.timedelta(hours=1), f1()) + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_sync_return_no_value(self): + @gen.coroutine + def f(): + return + + result = yield f() + self.assertIsNone(result) + self.finished = True + + @gen_test + def test_async_return_no_value(self): + @gen.coroutine + def f(): + yield gen.moment + return + + result = yield f() + self.assertIsNone(result) + self.finished = True + + @gen_test + def test_sync_raise(self): + @gen.coroutine + def f(): + 1 / 0 + + # The exception is raised when the future is yielded + # (or equivalently when its result method is called), + # not when the function itself is called). + future = f() + with self.assertRaises(ZeroDivisionError): + yield future + self.finished = True + + @gen_test + def test_async_raise(self): + @gen.coroutine + def f(): + yield gen.moment + 1 / 0 + + future = f() + with self.assertRaises(ZeroDivisionError): + yield future + self.finished = True + + @gen_test + def test_replace_yieldpoint_exception(self): + # Test exception handling: a coroutine can catch one exception + # raised by a yield point and raise a different one. + @gen.coroutine + def f1(): + 1 / 0 + + @gen.coroutine + def f2(): + try: + yield f1() + except ZeroDivisionError: + raise KeyError() + + future = f2() + with self.assertRaises(KeyError): + yield future + self.finished = True + + @gen_test + def test_swallow_yieldpoint_exception(self): + # Test exception handling: a coroutine can catch an exception + # raised by a yield point and not raise a different one. + @gen.coroutine + def f1(): + 1 / 0 + + @gen.coroutine + def f2(): + try: + yield f1() + except ZeroDivisionError: + raise gen.Return(42) + + result = yield f2() + self.assertEqual(result, 42) + self.finished = True + + @gen_test + def test_moment(self): + calls = [] + + @gen.coroutine + def f(name, yieldable): + for i in range(5): + calls.append(name) + yield yieldable + + # First, confirm the behavior without moment: each coroutine + # monopolizes the event loop until it finishes. + immediate = Future() # type: Future[None] + immediate.set_result(None) + yield [f("a", immediate), f("b", immediate)] + self.assertEqual("".join(calls), "aaaaabbbbb") + + # With moment, they take turns. + calls = [] + yield [f("a", gen.moment), f("b", gen.moment)] + self.assertEqual("".join(calls), "ababababab") + self.finished = True + + calls = [] + yield [f("a", gen.moment), f("b", immediate)] + self.assertEqual("".join(calls), "abbbbbaaaa") + + @gen_test + def test_sleep(self): + yield gen.sleep(0.01) + self.finished = True + + @gen_test + def test_py3_leak_exception_context(self): + class LeakedException(Exception): + pass + + @gen.coroutine + def inner(iteration): + raise LeakedException(iteration) + + try: + yield inner(1) + except LeakedException as e: + self.assertEqual(str(e), "1") + self.assertIsNone(e.__context__) + + try: + yield inner(2) + except LeakedException as e: + self.assertEqual(str(e), "2") + self.assertIsNone(e.__context__) + + self.finished = True + + @skipNotCPython + def test_coroutine_refcounting(self): + # On CPython, tasks and their arguments should be released immediately + # without waiting for garbage collection. + @gen.coroutine + def inner(): + class Foo: + pass + + local_var = Foo() + self.local_ref = weakref.ref(local_var) + + def dummy(): + pass + + yield gen.coroutine(dummy)() + raise ValueError("Some error") + + @gen.coroutine + def inner2(): + try: + yield inner() + except ValueError: + pass + + self.io_loop.run_sync(inner2, timeout=3) + + self.assertIsNone(self.local_ref()) + self.finished = True + + def test_asyncio_future_debug_info(self): + self.finished = True + # Enable debug mode + asyncio_loop = asyncio.get_event_loop() + self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug()) + asyncio_loop.set_debug(True) + + def f(): + yield gen.moment + + coro = gen.coroutine(f)() + self.assertIsInstance(coro, asyncio.Future) + # We expect the coroutine repr() to show the place where + # it was instantiated + expected = "created at %s:%d" % (__file__, f.__code__.co_firstlineno + 3) + actual = repr(coro) + self.assertIn(expected, actual) + + @gen_test + def test_asyncio_gather(self): + # This demonstrates that tornado coroutines can be understood + # by asyncio (This failed prior to Tornado 5.0). + @gen.coroutine + def f(): + yield gen.moment + raise gen.Return(1) + + ret = yield asyncio.gather(f(), f()) + self.assertEqual(ret, [1, 1]) + self.finished = True + + +class GenCoroutineSequenceHandler(RequestHandler): + @gen.coroutine + def get(self): + yield gen.moment + self.write("1") + yield gen.moment + self.write("2") + yield gen.moment + self.finish("3") + + +class GenCoroutineUnfinishedSequenceHandler(RequestHandler): + @gen.coroutine + def get(self): + yield gen.moment + self.write("1") + yield gen.moment + self.write("2") + yield gen.moment + # just write, don't finish + self.write("3") + + +# "Undecorated" here refers to the absence of @asynchronous. +class UndecoratedCoroutinesHandler(RequestHandler): + @gen.coroutine + def prepare(self): + self.chunks = [] # type: List[str] + yield gen.moment + self.chunks.append("1") + + @gen.coroutine + def get(self): + self.chunks.append("2") + yield gen.moment + self.chunks.append("3") + yield gen.moment + self.write("".join(self.chunks)) + + +class AsyncPrepareErrorHandler(RequestHandler): + @gen.coroutine + def prepare(self): + yield gen.moment + raise HTTPError(403) + + def get(self): + self.finish("ok") + + +class NativeCoroutineHandler(RequestHandler): + async def get(self): + await asyncio.sleep(0) + self.write("ok") + + +class GenWebTest(AsyncHTTPTestCase): + def get_app(self): + return Application( + [ + ("/coroutine_sequence", GenCoroutineSequenceHandler), + ( + "/coroutine_unfinished_sequence", + GenCoroutineUnfinishedSequenceHandler, + ), + ("/undecorated_coroutine", UndecoratedCoroutinesHandler), + ("/async_prepare_error", AsyncPrepareErrorHandler), + ("/native_coroutine", NativeCoroutineHandler), + ] + ) + + def test_coroutine_sequence_handler(self): + response = self.fetch("/coroutine_sequence") + self.assertEqual(response.body, b"123") + + def test_coroutine_unfinished_sequence_handler(self): + response = self.fetch("/coroutine_unfinished_sequence") + self.assertEqual(response.body, b"123") + + def test_undecorated_coroutines(self): + response = self.fetch("/undecorated_coroutine") + self.assertEqual(response.body, b"123") + + def test_async_prepare_error_handler(self): + response = self.fetch("/async_prepare_error") + self.assertEqual(response.code, 403) + + def test_native_coroutine_handler(self): + response = self.fetch("/native_coroutine") + self.assertEqual(response.code, 200) + self.assertEqual(response.body, b"ok") + + +class WithTimeoutTest(AsyncTestCase): + @gen_test + def test_timeout(self): + with self.assertRaises(gen.TimeoutError): + yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future()) + + @gen_test + def test_completes_before_timeout(self): + future = Future() # type: Future[str] + self.io_loop.add_timeout( + datetime.timedelta(seconds=0.1), lambda: future.set_result("asdf") + ) + result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future) + self.assertEqual(result, "asdf") + + @gen_test + def test_fails_before_timeout(self): + future = Future() # type: Future[str] + self.io_loop.add_timeout( + datetime.timedelta(seconds=0.1), + lambda: future.set_exception(ZeroDivisionError()), + ) + with self.assertRaises(ZeroDivisionError): + yield gen.with_timeout(datetime.timedelta(seconds=3600), future) + + @gen_test + def test_already_resolved(self): + future = Future() # type: Future[str] + future.set_result("asdf") + result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future) + self.assertEqual(result, "asdf") + + @gen_test + def test_timeout_concurrent_future(self): + # A concurrent future that does not resolve before the timeout. + with futures.ThreadPoolExecutor(1) as executor: + with self.assertRaises(gen.TimeoutError): + yield gen.with_timeout( + self.io_loop.time(), executor.submit(time.sleep, 0.1) + ) + + @gen_test + def test_completed_concurrent_future(self): + # A concurrent future that is resolved before we even submit it + # to with_timeout. + with futures.ThreadPoolExecutor(1) as executor: + + def dummy(): + pass + + f = executor.submit(dummy) + f.result() # wait for completion + yield gen.with_timeout(datetime.timedelta(seconds=3600), f) + + @gen_test + def test_normal_concurrent_future(self): + # A conccurrent future that resolves while waiting for the timeout. + with futures.ThreadPoolExecutor(1) as executor: + yield gen.with_timeout( + datetime.timedelta(seconds=3600), + executor.submit(lambda: time.sleep(0.01)), + ) + + +class WaitIteratorTest(AsyncTestCase): + @gen_test + def test_empty_iterator(self): + g = gen.WaitIterator() + self.assertTrue(g.done(), "empty generator iterated") + + with self.assertRaises(ValueError): + g = gen.WaitIterator(Future(), bar=Future()) + + self.assertIsNone(g.current_index, "bad nil current index") + self.assertIsNone(g.current_future, "bad nil current future") + + @gen_test + def test_already_done(self): + f1 = Future() # type: Future[int] + f2 = Future() # type: Future[int] + f3 = Future() # type: Future[int] + f1.set_result(24) + f2.set_result(42) + f3.set_result(84) + + g = gen.WaitIterator(f1, f2, f3) + i = 0 + while not g.done(): + r = yield g.next() + # Order is not guaranteed, but the current implementation + # preserves ordering of already-done Futures. + if i == 0: + self.assertEqual(g.current_index, 0) + self.assertIs(g.current_future, f1) + self.assertEqual(r, 24) + elif i == 1: + self.assertEqual(g.current_index, 1) + self.assertIs(g.current_future, f2) + self.assertEqual(r, 42) + elif i == 2: + self.assertEqual(g.current_index, 2) + self.assertIs(g.current_future, f3) + self.assertEqual(r, 84) + i += 1 + + self.assertIsNone(g.current_index, "bad nil current index") + self.assertIsNone(g.current_future, "bad nil current future") + + dg = gen.WaitIterator(f1=f1, f2=f2) + + while not dg.done(): + dr = yield dg.next() + if dg.current_index == "f1": + self.assertTrue( + dg.current_future == f1 and dr == 24, + "WaitIterator dict status incorrect", + ) + elif dg.current_index == "f2": + self.assertTrue( + dg.current_future == f2 and dr == 42, + "WaitIterator dict status incorrect", + ) + else: + self.fail(f"got bad WaitIterator index {dg.current_index}") + + i += 1 + self.assertIsNone(g.current_index, "bad nil current index") + self.assertIsNone(g.current_future, "bad nil current future") + + def finish_coroutines(self, iteration, futures): + if iteration == 3: + futures[2].set_result(24) + elif iteration == 5: + futures[0].set_exception(ZeroDivisionError()) + elif iteration == 8: + futures[1].set_result(42) + futures[3].set_result(84) + + if iteration < 8: + self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures) + + @gen_test + def test_iterator(self): + futures = [Future(), Future(), Future(), Future()] # type: List[Future[int]] + + self.finish_coroutines(0, futures) + + g = gen.WaitIterator(*futures) + + i = 0 + while not g.done(): + try: + r = yield g.next() + except ZeroDivisionError: + self.assertIs(g.current_future, futures[0], "exception future invalid") + else: + if i == 0: + self.assertEqual(r, 24, "iterator value incorrect") + self.assertEqual(g.current_index, 2, "wrong index") + elif i == 2: + self.assertEqual(r, 42, "iterator value incorrect") + self.assertEqual(g.current_index, 1, "wrong index") + elif i == 3: + self.assertEqual(r, 84, "iterator value incorrect") + self.assertEqual(g.current_index, 3, "wrong index") + i += 1 + + @gen_test + def test_iterator_async_await(self): + # Recreate the previous test with py35 syntax. It's a little clunky + # because of the way the previous test handles an exception on + # a single iteration. + futures = [Future(), Future(), Future(), Future()] # type: List[Future[int]] + self.finish_coroutines(0, futures) + self.finished = False + + async def f(): + i = 0 + g = gen.WaitIterator(*futures) + try: + async for r in g: + if i == 0: + self.assertEqual(r, 24, "iterator value incorrect") + self.assertEqual(g.current_index, 2, "wrong index") + else: + raise Exception("expected exception on iteration 1") + i += 1 + except ZeroDivisionError: + i += 1 + async for r in g: + if i == 2: + self.assertEqual(r, 42, "iterator value incorrect") + self.assertEqual(g.current_index, 1, "wrong index") + elif i == 3: + self.assertEqual(r, 84, "iterator value incorrect") + self.assertEqual(g.current_index, 3, "wrong index") + else: + raise Exception("didn't expect iteration %d" % i) + i += 1 + self.finished = True + + yield f() + self.assertTrue(self.finished) + + @gen_test + def test_no_ref(self): + # In this usage, there is no direct hard reference to the + # WaitIterator itself, only the Future it returns. Since + # WaitIterator uses weak references internally to improve GC + # performance, this used to cause problems. + yield gen.with_timeout( + datetime.timedelta(seconds=0.1), gen.WaitIterator(gen.sleep(0)).next() + ) + + +class RunnerGCTest(AsyncTestCase): + def is_pypy3(self): + return platform.python_implementation() == "PyPy" and sys.version_info > (3,) + + @gen_test + def test_gc(self): + # GitHub issue 1769: Runner objects can get GCed unexpectedly + # while their future is alive. + weakref_scope = [None] # type: List[Optional[weakref.ReferenceType]] + + def callback(): + gc.collect(2) + weakref_scope[0]().set_result(123) # type: ignore + + @gen.coroutine + def tester(): + fut = Future() # type: Future[int] + weakref_scope[0] = weakref.ref(fut) + self.io_loop.add_callback(callback) + yield fut + + yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester()) + + def test_gc_infinite_coro(self): + # GitHub issue 2229: suspended coroutines should be GCed when + # their loop is closed, even if they're involved in a reference + # cycle. + loop = self.get_new_ioloop() + result = [] # type: List[Optional[bool]] + wfut = [] + + @gen.coroutine + def infinite_coro(): + try: + while True: + yield gen.sleep(1e-3) + result.append(True) + finally: + # coroutine finalizer + result.append(None) + + @gen.coroutine + def do_something(): + fut = infinite_coro() + fut._refcycle = fut # type: ignore + wfut.append(weakref.ref(fut)) + yield gen.sleep(0.2) + + loop.run_sync(do_something) + loop.close() + gc.collect() + # Future was collected + self.assertIsNone(wfut[0]()) + # At least one wakeup + self.assertGreaterEqual(len(result), 2) + if not self.is_pypy3(): + # coroutine finalizer was called (not on PyPy3 apparently) + self.assertIsNone(result[-1]) + + def test_gc_infinite_async_await(self): + # Same as test_gc_infinite_coro, but with a `async def` function + import asyncio + + async def infinite_coro(result): + try: + while True: + await gen.sleep(1e-3) + result.append(True) + finally: + # coroutine finalizer + result.append(None) + + loop = self.get_new_ioloop() + result = [] # type: List[Optional[bool]] + wfut = [] + + @gen.coroutine + def do_something(): + fut = asyncio.get_event_loop().create_task(infinite_coro(result)) + fut._refcycle = fut # type: ignore + wfut.append(weakref.ref(fut)) + yield gen.sleep(0.2) + + loop.run_sync(do_something) + with ExpectLog("asyncio", "Task was destroyed but it is pending"): + loop.close() + gc.collect() + # Future was collected + self.assertIsNone(wfut[0]()) + # At least one wakeup and one finally + self.assertGreaterEqual(len(result), 2) + if not self.is_pypy3(): + # coroutine finalizer was called (not on PyPy3 apparently) + self.assertIsNone(result[-1]) + + def test_multi_moment(self): + # Test gen.multi with moment + # now that it's not a real Future + @gen.coroutine + def wait_a_moment(): + result = yield gen.multi([gen.moment, gen.moment]) + raise gen.Return(result) + + loop = self.get_new_ioloop() + result = loop.run_sync(wait_a_moment) + self.assertEqual(result, [None, None]) + + +if contextvars is not None: + ctx_var = contextvars.ContextVar("ctx_var") # type: contextvars.ContextVar[int] + + +@unittest.skipIf(contextvars is None, "contextvars module not present") +class ContextVarsTest(AsyncTestCase): + async def native_root(self, x): + ctx_var.set(x) + await self.inner(x) + + @gen.coroutine + def gen_root(self, x): + ctx_var.set(x) + yield + yield self.inner(x) + + async def inner(self, x): + self.assertEqual(ctx_var.get(), x) + await self.gen_inner(x) + self.assertEqual(ctx_var.get(), x) + + # IOLoop.run_in_executor doesn't automatically copy context + ctx = contextvars.copy_context() + await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x)) + self.assertEqual(ctx_var.get(), x) + + # Neither does asyncio's run_in_executor. + await asyncio.get_event_loop().run_in_executor( + None, lambda: ctx.run(self.thread_inner, x) + ) + self.assertEqual(ctx_var.get(), x) + + @gen.coroutine + def gen_inner(self, x): + self.assertEqual(ctx_var.get(), x) + yield + self.assertEqual(ctx_var.get(), x) + + def thread_inner(self, x): + self.assertEqual(ctx_var.get(), x) + + @gen_test + def test_propagate(self): + # Verify that context vars get propagated across various + # combinations of native and decorated coroutines. + yield [ + self.native_root(1), + self.native_root(2), + self.gen_root(3), + self.gen_root(4), + ] + + @gen_test + def test_reset(self): + token = ctx_var.set(1) + yield + # reset asserts that we are still at the same level of the context tree, + # so we must make sure that we maintain that property across yield. + ctx_var.reset(token) + + @gen_test + def test_propagate_to_first_yield_with_native_async_function(self): + x = 10 + + async def native_async_function(): + self.assertEqual(ctx_var.get(), x) + + ctx_var.set(x) + yield native_async_function() + + +if __name__ == "__main__": + unittest.main() diff --git a/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo b/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo new file mode 100644 index 0000000000000000000000000000000000000000..a97bf9c57460ecfc27761accf90d712ea5cebb44 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo differ diff --git a/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po b/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po new file mode 100644 index 0000000000000000000000000000000000000000..8a6731c7cba4b74132b8af67402b044101ca386f --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po @@ -0,0 +1,47 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2015-01-27 11:05+0300\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: extract_me.py:11 +msgid "school" +msgstr "école" + +#: extract_me.py:12 +msgctxt "law" +msgid "right" +msgstr "le droit" + +#: extract_me.py:13 +msgctxt "good" +msgid "right" +msgstr "le bien" + +#: extract_me.py:14 +msgctxt "organization" +msgid "club" +msgid_plural "clubs" +msgstr[0] "le club" +msgstr[1] "les clubs" + +#: extract_me.py:15 +msgctxt "stick" +msgid "club" +msgid_plural "clubs" +msgstr[0] "le bâton" +msgstr[1] "les bâtons" diff --git a/python/user_packages/Python313/site-packages/tornado/test/http1connection_test.py b/python/user_packages/Python313/site-packages/tornado/test/http1connection_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9f9c70d5755b529e4b0cd143fde89d8135a5c1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/http1connection_test.py @@ -0,0 +1,61 @@ +import socket +import typing # noqa(F401) + +from tornado.http1connection import HTTP1Connection +from tornado.httputil import HTTPMessageDelegate +from tornado.iostream import IOStream +from tornado.locks import Event +from tornado.netutil import add_accept_handler +from tornado.testing import AsyncTestCase, bind_unused_port, gen_test + + +class HTTP1ConnectionTest(AsyncTestCase): + code = None # type: typing.Optional[int] + + def setUp(self): + super().setUp() + self.asyncSetUp() + + @gen_test + def asyncSetUp(self): + listener, port = bind_unused_port() + event = Event() + + def accept_callback(conn, addr): + self.server_stream = IOStream(conn) + self.addCleanup(self.server_stream.close) + event.set() + + add_accept_handler(listener, accept_callback) + self.client_stream = IOStream(socket.socket()) + self.addCleanup(self.client_stream.close) + yield [self.client_stream.connect(("127.0.0.1", port)), event.wait()] + self.io_loop.remove_handler(listener) + listener.close() + + @gen_test + def test_http10_no_content_length(self): + # Regression test for a bug in which can_keep_alive would crash + # for an HTTP/1.0 (not 1.1) response with no content-length. + conn = HTTP1Connection(self.client_stream, True) + self.server_stream.write(b"HTTP/1.0 200 Not Modified\r\n\r\nhello") + self.server_stream.close() + + event = Event() + test = self + body = [] + + class Delegate(HTTPMessageDelegate): + def headers_received(self, start_line, headers): + test.code = start_line.code + + def data_received(self, data): + body.append(data) + + def finish(self): + event.set() + + yield conn.read_response(Delegate()) + yield event.wait() + self.assertEqual(self.code, 200) + self.assertEqual(b"".join(body), b"hello") diff --git a/python/user_packages/Python313/site-packages/tornado/test/httpclient_test.py b/python/user_packages/Python313/site-packages/tornado/test/httpclient_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ee93393d359c1a570e355c33e4e7df14fee141b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/httpclient_test.py @@ -0,0 +1,957 @@ +import base64 +import binascii +from contextlib import closing +import copy +import gzip +import threading +import datetime +from io import BytesIO +import subprocess +import sys +import time +import typing # noqa: F401 +import unicodedata +import unittest + +from tornado.escape import utf8, native_str, to_unicode +from tornado import gen +from tornado.httpclient import ( + HTTPRequest, + HTTPResponse, + _RequestProxy, + HTTPError, + HTTPClient, +) +from tornado.httpserver import HTTPServer +from tornado.ioloop import IOLoop +from tornado.iostream import IOStream +from tornado.log import gen_log, app_log +from tornado import netutil +from tornado.testing import AsyncHTTPTestCase, bind_unused_port, gen_test, ExpectLog +from tornado.test.util import ignore_deprecation +from tornado.web import Application, RequestHandler, url +from tornado.httputil import format_timestamp, HTTPHeaders + + +class HelloWorldHandler(RequestHandler): + def get(self): + name = self.get_argument("name", "world") + self.set_header("Content-Type", "text/plain") + self.finish("Hello %s!" % name) + + +class PostHandler(RequestHandler): + def post(self): + self.finish( + "Post arg1: %s, arg2: %s" + % (self.get_argument("arg1"), self.get_argument("arg2")) + ) + + +class PutHandler(RequestHandler): + def put(self): + self.write("Put body: ") + self.write(self.request.body) + + +class RedirectHandler(RequestHandler): + def prepare(self): + self.write("redirects can have bodies too") + self.redirect( + self.get_argument("url"), status=int(self.get_argument("status", "302")) + ) + + +class RedirectWithoutLocationHandler(RequestHandler): + def prepare(self): + # For testing error handling of a redirect with no location header. + self.set_status(301) + self.finish() + + +class ChunkHandler(RequestHandler): + @gen.coroutine + def get(self): + self.write("asdf") + self.flush() + # Wait a bit to ensure the chunks are sent and received separately. + yield gen.sleep(0.01) + self.write("qwer") + + +class AuthHandler(RequestHandler): + def get(self): + self.finish(self.request.headers["Authorization"]) + + +class CountdownHandler(RequestHandler): + def get(self, count): + count = int(count) + if count > 0: + self.redirect(self.reverse_url("countdown", count - 1)) + else: + self.write("Zero") + + +class EchoPostHandler(RequestHandler): + def post(self): + self.write(self.request.body) + + +class UserAgentHandler(RequestHandler): + def get(self): + self.write(self.request.headers.get("User-Agent", "User agent not set")) + + +class ContentLength304Handler(RequestHandler): + def get(self): + self.set_status(304) + self.set_header("Content-Length", 42) + + def _clear_representation_headers(self): + # Tornado strips content-length from 304 responses, but here we + # want to simulate servers that include the headers anyway. + pass + + +class PatchHandler(RequestHandler): + def patch(self): + "Return the request payload - so we can check it is being kept" + self.write(self.request.body) + + +class AllMethodsHandler(RequestHandler): + SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ("OTHER",) # type: ignore + + def method(self): + assert self.request.method is not None + self.write(self.request.method) + + get = head = post = put = delete = options = patch = other = method # type: ignore + + +class SetHeaderHandler(RequestHandler): + def get(self): + # Use get_arguments for keys to get strings, but + # request.arguments for values to get bytes. + for k, v in zip(self.get_arguments("k"), self.request.arguments["v"]): + self.set_header(k, v) + + +class InvalidGzipHandler(RequestHandler): + def get(self) -> None: + # set Content-Encoding manually to avoid automatic gzip encoding + self.set_header("Content-Type", "text/plain") + self.set_header("Content-Encoding", "gzip") + # Triggering the potential bug seems to depend on input length. + # This length is taken from the bad-response example reported in + # https://github.com/tornadoweb/tornado/pull/2875 (uncompressed). + text = "".join(f"Hello World {i}\n" for i in range(9000))[:149051] + body = gzip.compress(text.encode(), compresslevel=6) + b"\00" + self.write(body) + + +class HeaderEncodingHandler(RequestHandler): + def get(self): + self.finish(self.request.headers["Foo"].encode("ISO8859-1")) + + +# These tests end up getting run redundantly: once here with the default +# HTTPClient implementation, and then again in each implementation's own +# test suite. + + +class HTTPClientCommonTestCase(AsyncHTTPTestCase): + def get_app(self): + return Application( + [ + url("/hello", HelloWorldHandler), + url("/post", PostHandler), + url("/put", PutHandler), + url("/redirect", RedirectHandler), + url("/redirect_without_location", RedirectWithoutLocationHandler), + url("/chunk", ChunkHandler), + url("/auth", AuthHandler), + url("/countdown/([0-9]+)", CountdownHandler, name="countdown"), + url("/echopost", EchoPostHandler), + url("/user_agent", UserAgentHandler), + url("/304_with_content_length", ContentLength304Handler), + url("/all_methods", AllMethodsHandler), + url("/patch", PatchHandler), + url("/set_header", SetHeaderHandler), + url("/invalid_gzip", InvalidGzipHandler), + url("/header-encoding", HeaderEncodingHandler), + ], + gzip=True, + ) + + def test_patch_receives_payload(self): + body = b"some patch data" + response = self.fetch("/patch", method="PATCH", body=body) + self.assertEqual(response.code, 200) + self.assertEqual(response.body, body) + + def test_hello_world(self): + response = self.fetch("/hello") + self.assertEqual(response.code, 200) + self.assertEqual(response.headers["Content-Type"], "text/plain") + self.assertEqual(response.body, b"Hello world!") + assert response.request_time is not None + self.assertEqual(int(response.request_time), 0) + + response = self.fetch("/hello?name=Ben") + self.assertEqual(response.body, b"Hello Ben!") + + def test_streaming_callback(self): + # streaming_callback is also tested in test_chunked + chunks = [] # type: typing.List[bytes] + response = self.fetch("/hello", streaming_callback=chunks.append) + # with streaming_callback, data goes to the callback and not response.body + self.assertEqual(chunks, [b"Hello world!"]) + self.assertFalse(response.body) + + def test_post(self): + response = self.fetch("/post", method="POST", body="arg1=foo&arg2=bar") + self.assertEqual(response.code, 200) + self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") + + def test_chunked(self): + response = self.fetch("/chunk") + self.assertEqual(response.body, b"asdfqwer") + + chunks = [] # type: typing.List[bytes] + response = self.fetch("/chunk", streaming_callback=chunks.append) + self.assertEqual(chunks, [b"asdf", b"qwer"]) + self.assertFalse(response.body) + + def test_chunked_close(self): + # test case in which chunks spread read-callback processing + # over several ioloop iterations, but the connection is already closed. + sock, port = bind_unused_port() + with closing(sock): + + @gen.coroutine + def accept_callback(conn, address): + # fake an HTTP server using chunked encoding where the final chunks + # and connection close all happen at once + stream = IOStream(conn) + request_data = yield stream.read_until(b"\r\n\r\n") + if b"HTTP/1." not in request_data: + self.skipTest("requires HTTP/1.x") + yield stream.write( + b"""\ +HTTP/1.1 200 OK +Transfer-Encoding: chunked + +1 +1 +1 +2 +0 + +""".replace( + b"\n", b"\r\n" + ) + ) + stream.close() + + netutil.add_accept_handler(sock, accept_callback) # type: ignore + resp = self.fetch("http://127.0.0.1:%d/" % port) + resp.rethrow() + self.assertEqual(resp.body, b"12") + self.io_loop.remove_handler(sock.fileno()) + + def test_basic_auth(self): + # This test data appears in section 2 of RFC 7617. + self.assertEqual( + self.fetch( + "/auth", auth_username="Aladdin", auth_password="open sesame" + ).body, + b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + ) + + def test_basic_auth_explicit_mode(self): + self.assertEqual( + self.fetch( + "/auth", + auth_username="Aladdin", + auth_password="open sesame", + auth_mode="basic", + ).body, + b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + ) + + def test_basic_auth_unicode(self): + # This test data appears in section 2.1 of RFC 7617. + self.assertEqual( + self.fetch("/auth", auth_username="test", auth_password="123£").body, + b"Basic dGVzdDoxMjPCow==", + ) + + # The standard mandates NFC. Give it a decomposed username + # and ensure it is normalized to composed form. + username = unicodedata.normalize("NFD", "josé") + self.assertEqual( + self.fetch("/auth", auth_username=username, auth_password="səcrət").body, + b"Basic am9zw6k6c8mZY3LJmXQ=", + ) + + def test_unsupported_auth_mode(self): + # curl and simple clients handle errors a bit differently; the + # important thing is that they don't fall back to basic auth + # on an unknown mode. + with ExpectLog(gen_log, "uncaught exception", required=False): + with self.assertRaises((ValueError, HTTPError)): # type: ignore + self.fetch( + "/auth", + auth_username="Aladdin", + auth_password="open sesame", + auth_mode="asdf", + raise_error=True, + ) + + def test_follow_redirect(self): + response = self.fetch("/countdown/2", follow_redirects=False) + self.assertEqual(302, response.code) + self.assertTrue(response.headers["Location"].endswith("/countdown/1")) + + response = self.fetch("/countdown/2") + self.assertEqual(200, response.code) + self.assertTrue(response.effective_url.endswith("/countdown/0")) + self.assertEqual(b"Zero", response.body) + + def test_redirect_without_location(self): + response = self.fetch("/redirect_without_location", follow_redirects=True) + # If there is no location header, the redirect response should + # just be returned as-is. (This should arguably raise an + # error, but libcurl doesn't treat this as an error, so we + # don't either). + self.assertEqual(301, response.code) + + def test_redirect_put_with_body(self): + response = self.fetch( + "/redirect?url=/put&status=307", method="PUT", body="hello" + ) + self.assertEqual(response.body, b"Put body: hello") + + def test_redirect_put_without_body(self): + # This "without body" edge case is similar to what happens with body_producer. + response = self.fetch( + "/redirect?url=/put&status=307", + method="PUT", + allow_nonstandard_methods=True, + ) + self.assertEqual(response.body, b"Put body: ") + + def test_method_after_redirect(self): + # Legacy redirect codes (301, 302) convert POST requests to GET. + for status in [301, 302, 303]: + url = "/redirect?url=/all_methods&status=%d" % status + resp = self.fetch(url, method="POST", body=b"") + self.assertEqual(b"GET", resp.body) + + # Other methods are left alone, except for 303 redirect, depending on client + for method in ["GET", "OPTIONS", "PUT", "DELETE"]: + resp = self.fetch(url, method=method, allow_nonstandard_methods=True) + if status in [301, 302]: + self.assertEqual(utf8(method), resp.body) + else: + self.assertIn(resp.body, [utf8(method), b"GET"]) + + # HEAD is different so check it separately. + resp = self.fetch(url, method="HEAD") + self.assertEqual(200, resp.code) + self.assertEqual(b"", resp.body) + + # Newer redirects always preserve the original method. + for status in [307, 308]: + url = "/redirect?url=/all_methods&status=307" + for method in ["GET", "OPTIONS", "POST", "PUT", "DELETE"]: + resp = self.fetch(url, method=method, allow_nonstandard_methods=True) + self.assertEqual(method, to_unicode(resp.body)) + resp = self.fetch(url, method="HEAD") + self.assertEqual(200, resp.code) + self.assertEqual(b"", resp.body) + + def test_credentials_in_url(self): + url = self.get_url("/auth").replace("http://", "http://me:secret@") + response = self.fetch(url) + self.assertEqual(b"Basic " + base64.b64encode(b"me:secret"), response.body) + + def test_body_encoding(self): + unicode_body = "\xe9" + byte_body = binascii.a2b_hex(b"e9") + + # unicode string in body gets converted to utf8 + response = self.fetch( + "/echopost", + method="POST", + body=unicode_body, + headers={"Content-Type": "application/blah"}, + ) + self.assertEqual(response.headers["Content-Length"], "2") + self.assertEqual(response.body, utf8(unicode_body)) + + # byte strings pass through directly + response = self.fetch( + "/echopost", + method="POST", + body=byte_body, + headers={"Content-Type": "application/blah"}, + ) + self.assertEqual(response.headers["Content-Length"], "1") + self.assertEqual(response.body, byte_body) + + # Mixing unicode in headers and byte string bodies shouldn't + # break anything + response = self.fetch( + "/echopost", + method="POST", + body=byte_body, + headers={"Content-Type": "application/blah"}, + user_agent="foo", + ) + self.assertEqual(response.headers["Content-Length"], "1") + self.assertEqual(response.body, byte_body) + + def test_types(self): + response = self.fetch("/hello") + self.assertEqual(type(response.body), bytes) + self.assertEqual(type(response.headers["Content-Type"]), str) + self.assertEqual(type(response.code), int) + self.assertEqual(type(response.effective_url), str) + + def test_gzip(self): + # All the tests in this file should be using gzip, but this test + # ensures that it is in fact getting compressed, and also tests + # the httpclient's decompress=False option. + # Setting Accept-Encoding manually bypasses the client's + # decompression so we can see the raw data. + response = self.fetch( + "/chunk", decompress_response=False, headers={"Accept-Encoding": "gzip"} + ) + self.assertEqual(response.headers["Content-Encoding"], "gzip") + self.assertNotEqual(response.body, b"asdfqwer") + # Our test data gets bigger when gzipped. Oops. :) + # Chunked encoding bypasses the MIN_LENGTH check. + self.assertEqual(len(response.body), 34) + f = gzip.GzipFile(mode="r", fileobj=response.buffer) + self.assertEqual(f.read(), b"asdfqwer") + + def test_invalid_gzip(self): + # test if client hangs on tricky invalid gzip + # curl/simple httpclient have different behavior (exception, logging) + with ExpectLog( + gen_log, ".*Malformed HTTP message.*unconsumed gzip data", required=False + ): + try: + response = self.fetch("/invalid_gzip") + self.assertEqual(response.code, 200) + self.assertEqual(response.body[:14], b"Hello World 0\n") + except HTTPError: + pass # acceptable + + def test_header_callback(self): + first_line = [] + headers = {} + chunks = [] + + def header_callback(header_line): + if header_line.startswith("HTTP/1.1 101"): + # Upgrading to HTTP/2 + pass + elif header_line.startswith("HTTP/"): + first_line.append(header_line) + elif header_line != "\r\n": + k, v = header_line.split(":", 1) + headers[k.lower()] = v.strip() + + def streaming_callback(chunk): + # All header callbacks are run before any streaming callbacks, + # so the header data is available to process the data as it + # comes in. + self.assertEqual(headers["content-type"], "text/html; charset=UTF-8") + chunks.append(chunk) + + self.fetch( + "/chunk", + header_callback=header_callback, + streaming_callback=streaming_callback, + ) + self.assertEqual(len(first_line), 1, first_line) + self.assertRegex(first_line[0], "HTTP/[0-9]\\.[0-9] 200.*\r\n") + self.assertEqual(chunks, [b"asdf", b"qwer"]) + + def test_header_callback_to_parse_line(self): + # Make a request with header_callback and feed the headers to HTTPHeaders.parse_line. + # (Instead of HTTPHeaders.parse which is used in normal cases). Ensure that the resulting + # headers are as expected, and in particular do not have trailing whitespace added + # due to the final CRLF line. + headers = HTTPHeaders() + + def header_callback(line): + if line.startswith("HTTP/"): + # Ignore the first status line + return + headers.parse_line(line) + + self.fetch("/hello", header_callback=header_callback) + for k, v in headers.get_all(): + self.assertTrue(v == v.strip(), (k, v)) + + @gen_test + def test_configure_defaults(self): + defaults = dict(user_agent="TestDefaultUserAgent", allow_ipv6=False) + # Construct a new instance of the configured client class + client = self.http_client.__class__(force_instance=True, defaults=defaults) + try: + response = yield client.fetch(self.get_url("/user_agent")) + self.assertEqual(response.body, b"TestDefaultUserAgent") + finally: + client.close() + + def test_header_types(self): + # Header values may be passed as character or utf8 byte strings, + # in a plain dictionary or an HTTPHeaders object. + # Keys must always be the native str type. + # All combinations should have the same results on the wire. + for value in ["MyUserAgent", b"MyUserAgent"]: + for container in [dict, HTTPHeaders]: + headers = container() + headers["User-Agent"] = value + resp = self.fetch("/user_agent", headers=headers) + self.assertEqual( + resp.body, + b"MyUserAgent", + "response=%r, value=%r, container=%r" + % (resp.body, value, container), + ) + + def test_multi_line_headers(self): + # Multi-line http headers are rare but rfc-allowed + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 + sock, port = bind_unused_port() + with closing(sock): + + @gen.coroutine + def accept_callback(conn, address): + stream = IOStream(conn) + request_data = yield stream.read_until(b"\r\n\r\n") + if b"HTTP/1." not in request_data: + self.skipTest("requires HTTP/1.x") + yield stream.write( + b"""\ +HTTP/1.1 200 OK +X-XSS-Protection: 1; +\tmode=block + +""".replace( + b"\n", b"\r\n" + ) + ) + stream.close() + + netutil.add_accept_handler(sock, accept_callback) # type: ignore + try: + resp = self.fetch("http://127.0.0.1:%d/" % port) + resp.rethrow() + self.assertEqual(resp.headers["X-XSS-Protection"], "1; mode=block") + finally: + self.io_loop.remove_handler(sock.fileno()) + + @gen_test + def test_header_encoding(self): + response = yield self.http_client.fetch( + self.get_url("/header-encoding"), + headers={ + "Foo": "b\xe4r", + }, + ) + self.assertEqual(response.body, "b\xe4r".encode("ISO8859-1")) + + def test_304_with_content_length(self): + # According to the spec 304 responses SHOULD NOT include + # Content-Length or other entity headers, but some servers do it + # anyway. + # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 + response = self.fetch("/304_with_content_length") + self.assertEqual(response.code, 304) + self.assertEqual(response.headers["Content-Length"], "42") + + @gen_test + def test_future_interface(self): + response = yield self.http_client.fetch(self.get_url("/hello")) + self.assertEqual(response.body, b"Hello world!") + + @gen_test + def test_future_http_error(self): + with self.assertRaises(HTTPError) as context: + yield self.http_client.fetch(self.get_url("/notfound")) + assert context.exception is not None + assert context.exception.response is not None + self.assertEqual(context.exception.code, 404) + self.assertEqual(context.exception.response.code, 404) + + @gen_test + def test_future_http_error_no_raise(self): + response = yield self.http_client.fetch( + self.get_url("/notfound"), raise_error=False + ) + self.assertEqual(response.code, 404) + + @gen_test + def test_reuse_request_from_response(self): + # The response.request attribute should be an HTTPRequest, not + # a _RequestProxy. + # This test uses self.http_client.fetch because self.fetch calls + # self.get_url on the input unconditionally. + url = self.get_url("/hello") + response = yield self.http_client.fetch(url) + self.assertEqual(response.request.url, url) + self.assertTrue(isinstance(response.request, HTTPRequest)) + response2 = yield self.http_client.fetch(response.request) + self.assertEqual(response2.body, b"Hello world!") + + @gen_test + def test_bind_source_ip(self): + url = self.get_url("/hello") + request = HTTPRequest(url, network_interface="127.0.0.1") + response = yield self.http_client.fetch(request) + self.assertEqual(response.code, 200) + + with self.assertRaises((ValueError, HTTPError)) as context: # type: ignore + request = HTTPRequest(url, network_interface="not-interface-or-ip") + yield self.http_client.fetch(request) + self.assertIn("not-interface-or-ip", str(context.exception)) + + def test_all_methods(self): + for method in ["GET", "DELETE", "OPTIONS"]: + response = self.fetch("/all_methods", method=method) + self.assertEqual(response.body, utf8(method)) + for method in ["POST", "PUT", "PATCH"]: + response = self.fetch("/all_methods", method=method, body=b"") + self.assertEqual(response.body, utf8(method)) + response = self.fetch("/all_methods", method="HEAD") + self.assertEqual(response.body, b"") + response = self.fetch( + "/all_methods", method="OTHER", allow_nonstandard_methods=True + ) + self.assertEqual(response.body, b"OTHER") + + def test_body_sanity_checks(self): + # These methods require a body. + for method in ("POST", "PUT", "PATCH"): + with self.assertRaises(ValueError) as context: + self.fetch("/all_methods", method=method, raise_error=True) + self.assertIn("must not be None", str(context.exception)) + + resp = self.fetch( + "/all_methods", method=method, allow_nonstandard_methods=True + ) + self.assertEqual(resp.code, 200) + + # These methods don't allow a body. + for method in ("GET", "DELETE", "OPTIONS"): + with self.assertRaises(ValueError) as context: + self.fetch( + "/all_methods", method=method, body=b"asdf", raise_error=True + ) + self.assertIn("must be None", str(context.exception)) + + # In most cases this can be overridden, but curl_httpclient + # does not allow body with a GET at all. + if method != "GET": + self.fetch( + "/all_methods", + method=method, + body=b"asdf", + allow_nonstandard_methods=True, + raise_error=True, + ) + self.assertEqual(resp.code, 200) + + # This test causes odd failures with the combination of + # curl_httpclient (at least with the version of libcurl available + # on ubuntu 12.04), TwistedIOLoop, and epoll. For POST (but not PUT), + # curl decides the response came back too soon and closes the connection + # to start again. It does this *before* telling the socket callback to + # unregister the FD. Some IOLoop implementations have special kernel + # integration to discover this immediately. Tornado's IOLoops + # ignore errors on remove_handler to accommodate this behavior, but + # Twisted's reactor does not. The removeReader call fails and so + # do all future removeAll calls (which our tests do at cleanup). + # + # def test_post_307(self): + # response = self.fetch("/redirect?status=307&url=/post", + # method="POST", body=b"arg1=foo&arg2=bar") + # self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") + + def test_put_307(self): + response = self.fetch( + "/redirect?status=307&url=/put", method="PUT", body=b"hello" + ) + response.rethrow() + self.assertEqual(response.body, b"Put body: hello") + + def test_non_ascii_header(self): + # Non-ascii headers are sent as latin1. + response = self.fetch("/set_header?k=foo&v=%E9") + response.rethrow() + self.assertEqual(response.headers["Foo"], native_str("\u00e9")) + + def test_response_times(self): + # A few simple sanity checks of the response time fields to + # make sure they're using the right basis (between the + # wall-time and monotonic clocks). + start_time = time.time() + response = self.fetch("/hello") + response.rethrow() + self.assertIsNotNone(response.request_time) + assert response.request_time is not None # for mypy + self.assertGreaterEqual(response.request_time, 0) + self.assertLess(response.request_time, 1.0) + # A very crude check to make sure that start_time is based on + # wall time and not the monotonic clock. + self.assertIsNotNone(response.start_time) + assert response.start_time is not None # for mypy + self.assertLess(abs(response.start_time - start_time), 1.0) + + for k, v in response.time_info.items(): + self.assertTrue(0 <= v < 1.0, f"time_info[{k}] out of bounds: {v}") + + def test_zero_timeout(self): + response = self.fetch("/hello", connect_timeout=0) + self.assertEqual(response.code, 200) + + response = self.fetch("/hello", request_timeout=0) + self.assertEqual(response.code, 200) + + response = self.fetch("/hello", connect_timeout=0, request_timeout=0) + self.assertEqual(response.code, 200) + + @gen_test + def test_error_after_cancel(self): + fut = self.http_client.fetch(self.get_url("/404")) + self.assertTrue(fut.cancel()) + with ExpectLog(app_log, "Exception after Future was cancelled") as el: + # We can't wait on the cancelled Future any more, so just + # let the IOLoop run until the exception gets logged (or + # not, in which case we exit the loop and ExpectLog will + # raise). + for i in range(100): + yield gen.sleep(0.01) + if el.logged_stack: + break + + def test_header_crlf(self): + # Ensure that the client doesn't allow CRLF injection in headers. RFC 9112 section 2.2 + # prohibits a bare CR specifically and "a recipient MAY recognize a single LF as a line + # terminator" so we check each character separately as well as the (redundant) CRLF pair. + for header, name in [ + ("foo\rbar:", "cr"), + ("foo\nbar:", "lf"), + ("foo\r\nbar:", "crlf"), + ]: + with self.subTest(name=name, position="value"): + with self.assertRaises(ValueError): + self.fetch("/hello", headers={"foo": header}) + with self.subTest(name=name, position="key"): + with self.assertRaises(ValueError): + self.fetch("/hello", headers={header: "foo"}) + + +class RequestProxyTest(unittest.TestCase): + def test_request_set(self): + proxy = _RequestProxy( + HTTPRequest("http://example.com/", user_agent="foo"), dict() + ) + self.assertEqual(proxy.user_agent, "foo") + + def test_default_set(self): + proxy = _RequestProxy( + HTTPRequest("http://example.com/"), dict(network_interface="foo") + ) + self.assertEqual(proxy.network_interface, "foo") + + def test_both_set(self): + proxy = _RequestProxy( + HTTPRequest("http://example.com/", proxy_host="foo"), dict(proxy_host="bar") + ) + self.assertEqual(proxy.proxy_host, "foo") + + def test_neither_set(self): + proxy = _RequestProxy(HTTPRequest("http://example.com/"), dict()) + self.assertIsNone(proxy.auth_username) + + def test_bad_attribute(self): + proxy = _RequestProxy(HTTPRequest("http://example.com/"), dict()) + with self.assertRaises(AttributeError): + proxy.foo + + def test_defaults_none(self): + proxy = _RequestProxy(HTTPRequest("http://example.com/"), None) + self.assertIsNone(proxy.auth_username) + + +class HTTPResponseTestCase(unittest.TestCase): + def test_str(self): + response = HTTPResponse( # type: ignore + HTTPRequest("http://example.com"), 200, buffer=BytesIO() + ) + s = str(response) + self.assertTrue(s.startswith("HTTPResponse(")) + self.assertIn("code=200", s) + + +class SyncHTTPClientTest(unittest.TestCase): + def setUp(self): + self.server_ioloop = IOLoop(make_current=False) + event = threading.Event() + + @gen.coroutine + def init_server(): + sock, self.port = bind_unused_port() + app = Application([("/", HelloWorldHandler)]) + self.server = HTTPServer(app) + self.server.add_socket(sock) + event.set() + + def start(): + self.server_ioloop.run_sync(init_server) + self.server_ioloop.start() + + self.server_thread = threading.Thread(target=start) + self.server_thread.start() + event.wait() + + self.http_client = HTTPClient() + + def tearDown(self): + def stop_server(): + self.server.stop() + # Delay the shutdown of the IOLoop by several iterations because + # the server may still have some cleanup work left when + # the client finishes with the response (this is noticeable + # with http/2, which leaves a Future with an unexamined + # StreamClosedError on the loop). + + @gen.coroutine + def slow_stop(): + yield self.server.close_all_connections() + # The number of iterations is difficult to predict. Typically, + # one is sufficient, although sometimes it needs more. + for i in range(5): + yield + self.server_ioloop.stop() + + self.server_ioloop.add_callback(slow_stop) + + self.server_ioloop.add_callback(stop_server) + self.server_thread.join() + self.http_client.close() + self.server_ioloop.close(all_fds=True) + + def get_url(self, path): + return "http://127.0.0.1:%d%s" % (self.port, path) + + def test_sync_client(self): + response = self.http_client.fetch(self.get_url("/")) + self.assertEqual(b"Hello world!", response.body) + + def test_sync_client_error(self): + # Synchronous HTTPClient raises errors directly; no need for + # response.rethrow() + with self.assertRaises(HTTPError) as assertion: + self.http_client.fetch(self.get_url("/notfound")) + self.assertEqual(assertion.exception.code, 404) + + +class SyncHTTPClientSubprocessTest(unittest.TestCase): + def test_destructor_log(self): + # Regression test for + # https://github.com/tornadoweb/tornado/issues/2539 + # + # In the past, the following program would log an + # "inconsistent AsyncHTTPClient cache" error from a destructor + # when the process is shutting down. The shutdown process is + # subtle and I don't fully understand it; the failure does not + # manifest if that lambda isn't there or is a simpler object + # like an int (nor does it manifest in the tornado test suite + # as a whole, which is why we use this subprocess). + proc = subprocess.run( + [ + sys.executable, + "-c", + "from tornado.httpclient import HTTPClient; f = lambda: None; c = HTTPClient()", + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=True, + timeout=15, + ) + if proc.stdout: + print("STDOUT:") + print(to_unicode(proc.stdout)) + if proc.stdout: + self.fail("subprocess produced unexpected output") + + +class HTTPRequestTestCase(unittest.TestCase): + def test_headers(self): + request = HTTPRequest("http://example.com", headers={"foo": "bar"}) + self.assertEqual(request.headers, {"foo": "bar"}) + + def test_headers_setter(self): + request = HTTPRequest("http://example.com") + request.headers = {"bar": "baz"} # type: ignore + self.assertEqual(request.headers, {"bar": "baz"}) + + def test_null_headers_setter(self): + request = HTTPRequest("http://example.com") + request.headers = None # type: ignore + self.assertEqual(request.headers, {}) + + def test_body(self): + request = HTTPRequest("http://example.com", body="foo") + self.assertEqual(request.body, utf8("foo")) + + def test_body_setter(self): + request = HTTPRequest("http://example.com") + request.body = "foo" # type: ignore + self.assertEqual(request.body, utf8("foo")) + + def test_if_modified_since(self): + http_date = datetime.datetime.now(datetime.timezone.utc) + request = HTTPRequest("http://example.com", if_modified_since=http_date) + self.assertEqual( + request.headers, {"If-Modified-Since": format_timestamp(http_date)} + ) + + def test_if_modified_since_naive_deprecated(self): + with ignore_deprecation(): + http_date = datetime.datetime.utcnow() + request = HTTPRequest("http://example.com", if_modified_since=http_date) + self.assertEqual( + request.headers, {"If-Modified-Since": format_timestamp(http_date)} + ) + + +class HTTPErrorTestCase(unittest.TestCase): + def test_copy(self): + e = HTTPError(403) + e2 = copy.copy(e) + self.assertIsNot(e, e2) + self.assertEqual(e.code, e2.code) + + def test_plain_error(self): + e = HTTPError(403) + self.assertEqual(str(e), "HTTP 403: Forbidden") + self.assertEqual(repr(e), "HTTP 403: Forbidden") + + def test_error_with_response(self): + resp = HTTPResponse(HTTPRequest("http://example.com/"), 403) + with self.assertRaises(HTTPError) as cm: + resp.rethrow() + e = cm.exception + self.assertEqual(str(e), "HTTP 403: Forbidden") + self.assertEqual(repr(e), "HTTP 403: Forbidden") diff --git a/python/user_packages/Python313/site-packages/tornado/test/httpserver_test.py b/python/user_packages/Python313/site-packages/tornado/test/httpserver_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c607f975a8672228f4bf889e17aa70e8ad93e952 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/httpserver_test.py @@ -0,0 +1,1535 @@ +from tornado import gen, netutil +from tornado.escape import ( + json_decode, + json_encode, + utf8, + _unicode, + recursive_unicode, + native_str, +) +from tornado.http1connection import HTTP1Connection +from tornado.httpclient import HTTPError +from tornado.httpserver import HTTPServer +from tornado.httputil import ( + HTTPHeaders, + HTTPMessageDelegate, + HTTPServerConnectionDelegate, + ResponseStartLine, +) +from tornado.iostream import IOStream +from tornado.locks import Event +from tornado.log import gen_log, app_log +from tornado.simple_httpclient import SimpleAsyncHTTPClient +from tornado.testing import ( + AsyncHTTPTestCase, + AsyncHTTPSTestCase, + AsyncTestCase, + ExpectLog, + gen_test, +) +from tornado.test.util import abstract_base_test +from tornado.web import Application, RequestHandler, stream_request_body + +from contextlib import closing, contextmanager +import datetime +import gzip +import logging +import os +import shutil +import socket +import ssl +import sys +import tempfile +import textwrap +import unittest +import urllib.parse +import uuid +from io import BytesIO + +import typing + +if typing.TYPE_CHECKING: + from typing import Dict, List # noqa: F401 + + +async def read_stream_body(stream): + """Reads an HTTP response from `stream` and returns a tuple of its + start_line, headers and body.""" + chunks = [] + + class Delegate(HTTPMessageDelegate): + def headers_received(self, start_line, headers): + self.headers = headers + self.start_line = start_line + + def data_received(self, chunk): + chunks.append(chunk) + + def finish(self): + conn.detach() # type: ignore + + conn = HTTP1Connection(stream, True) + delegate = Delegate() + await conn.read_response(delegate) + return delegate.start_line, delegate.headers, b"".join(chunks) + + +class HandlerBaseTestCase(AsyncHTTPTestCase): + Handler = None + + def get_app(self): + return Application([("/", self.__class__.Handler)]) + + def fetch_json(self, *args, **kwargs): + response = self.fetch(*args, **kwargs) + response.rethrow() + return json_decode(response.body) + + +class HelloWorldRequestHandler(RequestHandler): + def initialize(self, protocol="http"): + self.expected_protocol = protocol + + def get(self): + if self.request.protocol != self.expected_protocol: + raise Exception("unexpected protocol") + self.finish("Hello world") + + def post(self): + self.finish("Got %d bytes in POST" % len(self.request.body)) + + +class SSLTest(AsyncHTTPSTestCase): + def get_app(self): + return Application([("/", HelloWorldRequestHandler, dict(protocol="https"))]) + + def get_ssl_options(self): + return dict( + ssl_version=ssl.PROTOCOL_TLS_SERVER, + **AsyncHTTPSTestCase.default_ssl_options(), + ) + + def test_ssl(self): + response = self.fetch("/") + self.assertEqual(response.body, b"Hello world") + + def test_large_post(self): + response = self.fetch("/", method="POST", body="A" * 5000) + self.assertEqual(response.body, b"Got 5000 bytes in POST") + + def test_non_ssl_request(self): + # Make sure the server closes the connection when it gets a non-ssl + # connection, rather than waiting for a timeout or otherwise + # misbehaving. + with ExpectLog(gen_log, "(SSL Error|uncaught exception)"): + with ExpectLog(gen_log, "Uncaught exception", required=False): + with self.assertRaises((IOError, HTTPError)): # type: ignore + self.fetch( + self.get_url("/").replace("https:", "http:"), + request_timeout=3600, + connect_timeout=3600, + raise_error=True, + ) + + def test_error_logging(self): + # No stack traces are logged for SSL errors. + with ExpectLog(gen_log, "SSL Error") as expect_log: + with self.assertRaises((IOError, HTTPError)): # type: ignore + self.fetch( + self.get_url("/").replace("https:", "http:"), raise_error=True + ) + self.assertFalse(expect_log.logged_stack) + + +class BadSSLOptionsTest(unittest.TestCase): + def test_missing_arguments(self): + application = Application() + self.assertRaises( + KeyError, + HTTPServer, + application, + ssl_options={"keyfile": "/__missing__.crt"}, + ) + + def test_missing_key(self): + """A missing SSL key should cause an immediate exception.""" + + application = Application() + module_dir = os.path.dirname(__file__) + existing_certificate = os.path.join(module_dir, "test.crt") + existing_key = os.path.join(module_dir, "test.key") + + self.assertRaises( + (ValueError, IOError), + HTTPServer, + application, + ssl_options={"certfile": "/__mising__.crt"}, + ) + self.assertRaises( + (ValueError, IOError), + HTTPServer, + application, + ssl_options={ + "certfile": existing_certificate, + "keyfile": "/__missing__.key", + }, + ) + + # This actually works because both files exist + HTTPServer( + application, + ssl_options={"certfile": existing_certificate, "keyfile": existing_key}, + ) + + +class MultipartTestHandler(RequestHandler): + def post(self): + self.finish( + { + "header": self.request.headers["X-Header-Encoding-Test"], + "argument": self.get_argument("argument"), + "filename": self.request.files["files"][0].filename, + "filebody": _unicode(self.request.files["files"][0]["body"]), + } + ) + + +# This test is also called from wsgi_test +class HTTPConnectionTest(AsyncHTTPTestCase): + def get_handlers(self): + return [ + ("/multipart", MultipartTestHandler), + ("/hello", HelloWorldRequestHandler), + ] + + def get_app(self): + return Application(self.get_handlers()) + + def raw_fetch(self, headers, body, newline=b"\r\n"): + with closing(IOStream(socket.socket())) as stream: + self.io_loop.run_sync( + lambda: stream.connect(("127.0.0.1", self.get_http_port())) + ) + stream.write( + newline.join(headers + [utf8("Content-Length: %d" % len(body))]) + + newline + + newline + + body + ) + start_line, headers, body = self.io_loop.run_sync( + lambda: read_stream_body(stream) + ) + return body + + def test_multipart_form(self): + # Encodings here are tricky: Headers are latin1, bodies can be + # anything (we use utf8 by default). + response = self.raw_fetch( + [ + b"POST /multipart HTTP/1.0", + b"Content-Type: multipart/form-data; boundary=1234567890", + b"X-Header-encoding-test: \xe9", + ], + b"\r\n".join( + [ + b"Content-Disposition: form-data; name=argument", + b"", + "\u00e1".encode(), + b"--1234567890", + 'Content-Disposition: form-data; name="files"; filename="\u00f3"'.encode(), + b"", + "\u00fa".encode(), + b"--1234567890--", + b"", + ] + ), + ) + data = json_decode(response) + self.assertEqual("\u00e9", data["header"]) + self.assertEqual("\u00e1", data["argument"]) + self.assertEqual("\u00f3", data["filename"]) + self.assertEqual("\u00fa", data["filebody"]) + + def test_newlines(self): + # We support both CRLF and bare LF as line separators. + for newline in (b"\r\n", b"\n"): + response = self.raw_fetch([b"GET /hello HTTP/1.0"], b"", newline=newline) + self.assertEqual(response, b"Hello world") + + @gen_test + def test_100_continue(self): + # Run through a 100-continue interaction by hand: + # When given Expect: 100-continue, we get a 100 response after the + # headers, and then the real response after the body. + stream = IOStream(socket.socket()) + yield stream.connect(("127.0.0.1", self.get_http_port())) + yield stream.write( + b"\r\n".join( + [ + b"POST /hello HTTP/1.1", + b"Host: 127.0.0.1", + b"Content-Length: 1024", + b"Expect: 100-continue", + b"Connection: close", + b"\r\n", + ] + ) + ) + data = yield stream.read_until(b"\r\n\r\n") + self.assertTrue(data.startswith(b"HTTP/1.1 100 "), data) + stream.write(b"a" * 1024) + first_line = yield stream.read_until(b"\r\n") + self.assertTrue(first_line.startswith(b"HTTP/1.1 200"), first_line) + header_data = yield stream.read_until(b"\r\n\r\n") + headers = HTTPHeaders.parse(native_str(header_data.decode("latin1"))) + body = yield stream.read_bytes(int(headers["Content-Length"])) + self.assertEqual(body, b"Got 1024 bytes in POST") + stream.close() + + +class EchoHandler(RequestHandler): + def get(self): + self.write(recursive_unicode(self.request.arguments)) + + def post(self): + self.write(recursive_unicode(self.request.arguments)) + + +class TypeCheckHandler(RequestHandler): + def prepare(self): + self.errors = {} # type: Dict[str, str] + fields = [ + ("method", str), + ("uri", str), + ("version", str), + ("remote_ip", str), + ("protocol", str), + ("host", str), + ("path", str), + ("query", str), + ] + for field, expected_type in fields: + self.check_type(field, getattr(self.request, field), expected_type) + + self.check_type("header_key", list(self.request.headers.keys())[0], str) + self.check_type("header_value", list(self.request.headers.values())[0], str) + + self.check_type("cookie_key", list(self.request.cookies.keys())[0], str) + self.check_type( + "cookie_value", list(self.request.cookies.values())[0].value, str + ) + # secure cookies + + self.check_type("arg_key", list(self.request.arguments.keys())[0], str) + self.check_type("arg_value", list(self.request.arguments.values())[0][0], bytes) + + def post(self): + self.check_type("body", self.request.body, bytes) + self.write(self.errors) + + def get(self): + self.write(self.errors) + + def check_type(self, name, obj, expected_type): + actual_type = type(obj) + if expected_type != actual_type: + self.errors[name] = f"expected {expected_type}, got {actual_type}" + + +class PostEchoHandler(RequestHandler): + def post(self, *path_args): + self.write(dict(echo=self.get_argument("data"))) + + +class PostEchoGBKHandler(PostEchoHandler): + def decode_argument(self, value, name=None): + try: + return value.decode("gbk") + except Exception: + raise HTTPError(400, "invalid gbk bytes: %r" % value) + + +class HTTPServerTest(AsyncHTTPTestCase): + def get_app(self): + return Application( + [ + ("/echo", EchoHandler), + ("/typecheck", TypeCheckHandler), + ("//doubleslash", EchoHandler), + ("/post_utf8", PostEchoHandler), + ("/post_gbk", PostEchoGBKHandler), + ] + ) + + def test_query_string_encoding(self): + response = self.fetch("/echo?foo=%C3%A9") + data = json_decode(response.body) + self.assertEqual(data, {"foo": ["\u00e9"]}) + + def test_empty_query_string(self): + response = self.fetch("/echo?foo=&foo=") + data = json_decode(response.body) + self.assertEqual(data, {"foo": ["", ""]}) + + def test_empty_post_parameters(self): + response = self.fetch("/echo", method="POST", body="foo=&bar=") + data = json_decode(response.body) + self.assertEqual(data, {"foo": [""], "bar": [""]}) + + def test_types(self): + headers = {"Cookie": "foo=bar"} + response = self.fetch("/typecheck?foo=bar", headers=headers) + data = json_decode(response.body) + self.assertEqual(data, {}) + + response = self.fetch( + "/typecheck", method="POST", body="foo=bar", headers=headers + ) + data = json_decode(response.body) + self.assertEqual(data, {}) + + def test_double_slash(self): + # urlparse.urlsplit (which tornado.httpserver used to use + # incorrectly) would parse paths beginning with "//" as + # protocol-relative urls. + response = self.fetch("//doubleslash") + self.assertEqual(200, response.code) + self.assertEqual(json_decode(response.body), {}) + + def test_post_encodings(self): + headers = {"Content-Type": "application/x-www-form-urlencoded"} + uni_text = "chinese: \u5f20\u4e09" + for enc in ("utf8", "gbk"): + for quote in (True, False): + with self.subTest(enc=enc, quote=quote): + bin_text = uni_text.encode(enc) + if quote: + bin_text = urllib.parse.quote(bin_text).encode("ascii") + response = self.fetch( + "/post_" + enc, + method="POST", + headers=headers, + body=(b"data=" + bin_text), + ) + self.assertEqual(json_decode(response.body), {"echo": uni_text}) + + +class HTTPServerRawTest(AsyncHTTPTestCase): + def get_app(self): + return Application([("/echo", EchoHandler)]) + + def setUp(self): + super().setUp() + self.stream = IOStream(socket.socket()) + self.io_loop.run_sync( + lambda: self.stream.connect(("127.0.0.1", self.get_http_port())) + ) + + def tearDown(self): + self.stream.close() + super().tearDown() + + def test_empty_request(self): + self.stream.close() + self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop) + self.wait() + + def test_malformed_first_line_response(self): + with ExpectLog(gen_log, ".*Malformed HTTP request line", level=logging.INFO): + self.stream.write(b"asdf\r\n\r\n") + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual("HTTP/1.1", start_line.version) + self.assertEqual(400, start_line.code) + self.assertEqual("Bad Request", start_line.reason) + + def test_malformed_first_line_log(self): + with ExpectLog(gen_log, ".*Malformed HTTP request line", level=logging.INFO): + self.stream.write(b"asdf\r\n\r\n") + # TODO: need an async version of ExpectLog so we don't need + # hard-coded timeouts here. + self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop) + self.wait() + + def test_malformed_headers(self): + with ExpectLog( + gen_log, + ".*Malformed HTTP message.*no colon in header line", + level=logging.INFO, + ): + self.stream.write(b"GET / HTTP/1.0\r\nasdf\r\n\r\n") + self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop) + self.wait() + + def test_invalid_host_header_with_whitespace(self): + with ExpectLog( + gen_log, ".*Malformed HTTP message.*Invalid Host header", level=logging.INFO + ): + self.stream.write(b"GET / HTTP/1.0\r\nHost: foo bar\r\n\r\n") + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual("HTTP/1.1", start_line.version) + self.assertEqual(400, start_line.code) + self.assertEqual("Bad Request", start_line.reason) + + def test_chunked_request_body(self): + # Chunked requests are not widely supported and we don't have a way + # to generate them in AsyncHTTPClient, but HTTPServer will read them. + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: chunked +Content-Type: application/x-www-form-urlencoded + +4 +foo= +3 +bar +0 + +""".replace( + b"\n", b"\r\n" + ) + ) + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(json_decode(response), {"foo": ["bar"]}) + + def test_chunked_request_uppercase(self): + # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value is + # case-insensitive. + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: Chunked +Content-Type: application/x-www-form-urlencoded + +4 +foo= +3 +bar +0 + +""".replace( + b"\n", b"\r\n" + ) + ) + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(json_decode(response), {"foo": ["bar"]}) + + def test_chunked_request_body_invalid_size(self): + # Only hex digits are allowed in chunk sizes. Python's int() function + # also accepts underscores, so make sure we reject them here. + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: chunked + +1_a +1234567890abcdef1234567890 +0 + +""".replace( + b"\n", b"\r\n" + ) + ) + with ExpectLog(gen_log, ".*invalid chunk size", level=logging.INFO): + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(400, start_line.code) + + def test_chunked_request_body_duplicate_header(self): + # Repeated Transfer-Encoding headers should be an error (and not confuse + # the chunked-encoding detection to mess up framing). + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: chunked +Transfer-encoding: chunked + +2 +ok +0 + +""" + ) + with ExpectLog( + gen_log, + ".*Unsupported Transfer-Encoding chunked,chunked", + level=logging.INFO, + ): + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(400, start_line.code) + + def test_chunked_request_body_unsupported_transfer_encoding(self): + # We don't support transfer-encodings other than chunked. + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: gzip, chunked + +2 +ok +0 + +""" + ) + with ExpectLog( + gen_log, ".*Unsupported Transfer-Encoding gzip, chunked", level=logging.INFO + ): + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(400, start_line.code) + + def test_chunked_request_body_transfer_encoding_and_content_length(self): + # Transfer-encoding and content-length are mutually exclusive + self.stream.write( + b"""\ +POST /echo HTTP/1.1 +Host: 127.0.0.1 +Transfer-Encoding: chunked +Content-Length: 2 + +2 +ok +0 + +""" + ) + with ExpectLog( + gen_log, + ".*Message with both Transfer-Encoding and Content-Length", + level=logging.INFO, + ): + start_line, headers, response = self.io_loop.run_sync( + lambda: read_stream_body(self.stream) + ) + self.assertEqual(400, start_line.code) + + @gen_test + def test_invalid_content_length(self): + # HTTP only allows decimal digits in content-length. Make sure we don't + # accept anything else, with special attention to things accepted by the + # python int() function (leading plus signs and internal underscores). + test_cases = [ + ("alphabetic", "foo"), + ("leading plus", "+10"), + ("internal underscore", "1_0"), + ] + for name, value in test_cases: + with self.subTest(name=name), closing(IOStream(socket.socket())) as stream: + with ExpectLog( + gen_log, + ".*Only integer Content-Length is allowed", + level=logging.INFO, + ): + yield stream.connect(("127.0.0.1", self.get_http_port())) + stream.write( + utf8( + textwrap.dedent( + f"""\ + POST /echo HTTP/1.1 + Host: 127.0.0.1 + Content-Length: {value} + Connection: close + + 1234567890 + """ + ).replace("\n", "\r\n") + ) + ) + yield stream.read_until_close() + + @gen_test + def test_invalid_methods(self): + # RFC 9110 distinguishes between syntactically invalid methods and those that are + # valid but unknown. The former must give a 400 status code, while the latter should + # give a 405. + test_cases = [ + ("FOO", 405, None), + ("FOO,BAR", 400, ".*Malformed HTTP request line"), + ] + for method, code, log_msg in test_cases: + if log_msg is not None: + expect_log = ExpectLog(gen_log, log_msg, level=logging.INFO) + else: + + @contextmanager + def noop_context(): + yield + + expect_log = noop_context() # type: ignore + with ( + self.subTest(method=method), + closing(IOStream(socket.socket())) as stream, + expect_log, + ): + yield stream.connect(("127.0.0.1", self.get_http_port())) + stream.write(utf8(f"{method} /echo HTTP/1.1\r\nHost:127.0.0.1\r\n\r\n")) + resp = yield stream.read_until(b"\r\n\r\n") + self.assertTrue( + resp.startswith(b"HTTP/1.1 %d" % code), + f"expected status code {code} in {resp!r}", + ) + + +class XHeaderTest(HandlerBaseTestCase): + class Handler(RequestHandler): + def get(self): + self.set_header("request-version", self.request.version) + self.write( + dict( + remote_ip=self.request.remote_ip, + remote_protocol=self.request.protocol, + ) + ) + + def get_httpserver_options(self): + return dict(xheaders=True, trusted_downstream=["5.5.5.5"]) + + def test_ip_headers(self): + self.assertEqual(self.fetch_json("/")["remote_ip"], "127.0.0.1") + + valid_ipv4 = {"X-Real-IP": "4.4.4.4"} + self.assertEqual( + self.fetch_json("/", headers=valid_ipv4)["remote_ip"], "4.4.4.4" + ) + + valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4"} + self.assertEqual( + self.fetch_json("/", headers=valid_ipv4_list)["remote_ip"], "4.4.4.4" + ) + + valid_ipv6 = {"X-Real-IP": "2620:0:1cfe:face:b00c::3"} + self.assertEqual( + self.fetch_json("/", headers=valid_ipv6)["remote_ip"], + "2620:0:1cfe:face:b00c::3", + ) + + valid_ipv6_list = {"X-Forwarded-For": "::1, 2620:0:1cfe:face:b00c::3"} + self.assertEqual( + self.fetch_json("/", headers=valid_ipv6_list)["remote_ip"], + "2620:0:1cfe:face:b00c::3", + ) + + invalid_chars = {"X-Real-IP": "4.4.4.4 + +") + self.assertEqual(response.code, 400) + self.assertEqual(response.reason, "Unknown") + self.assertNotIn(b"script", response.body) + self.assertIn(b"Unknown", response.body) + + +class DateHeaderTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + self.write("hello") + + def test_date_header(self): + response = self.fetch("/") + header_date = email.utils.parsedate_to_datetime(response.headers["Date"]) + self.assertLess( + header_date - datetime.datetime.now(datetime.timezone.utc), + datetime.timedelta(seconds=2), + ) + + +class RaiseWithReasonTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + raise HTTPError(682, reason="Foo") + + def get_http_client(self): + # simple_httpclient only: curl doesn't expose the reason string + return SimpleAsyncHTTPClient() + + def test_raise_with_reason(self): + response = self.fetch("/") + self.assertEqual(response.code, 682) + self.assertEqual(response.reason, "Foo") + self.assertIn(b"682: Foo", response.body) + + def test_httperror_str(self): + self.assertEqual(str(HTTPError(682, reason="Foo")), "HTTP 682: Foo") + + def test_httperror_str_from_httputil(self): + self.assertEqual(str(HTTPError(682)), "HTTP 682: Unknown") + + +class ErrorHandlerXSRFTest(WebTestCase): + def get_handlers(self): + # note that if the handlers list is empty we get the default_host + # redirect fallback instead of a 404, so test with both an + # explicitly defined error handler and an implicit 404. + return [("/error", ErrorHandler, dict(status_code=417))] + + def get_app_kwargs(self): + return dict(xsrf_cookies=True) + + def test_error_xsrf(self): + response = self.fetch("/error", method="POST", body="") + self.assertEqual(response.code, 417) + + def test_404_xsrf(self): + response = self.fetch("/404", method="POST", body="") + self.assertEqual(response.code, 404) + + +class GzipTestCase(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + for v in self.get_arguments("vary"): + self.add_header("Vary", v) + # Must write at least MIN_LENGTH bytes to activate compression. + self.write("hello world" + ("!" * GZipContentEncoding.MIN_LENGTH)) + + def get_app_kwargs(self): + return dict( + gzip=True, static_path=os.path.join(os.path.dirname(__file__), "static") + ) + + def assert_compressed(self, response): + # simple_httpclient renames the content-encoding header; + # curl_httpclient doesn't. + self.assertEqual( + response.headers.get( + "Content-Encoding", response.headers.get("X-Consumed-Content-Encoding") + ), + "gzip", + ) + + def test_gzip(self): + response = self.fetch("/") + self.assert_compressed(response) + self.assertEqual(response.headers["Vary"], "Accept-Encoding") + + def test_gzip_static(self): + # The streaming responses in StaticFileHandler have subtle + # interactions with the gzip output so test this case separately. + response = self.fetch("/robots.txt") + self.assert_compressed(response) + self.assertEqual(response.headers["Vary"], "Accept-Encoding") + + def test_gzip_not_requested(self): + response = self.fetch("/", use_gzip=False) + self.assertNotIn("Content-Encoding", response.headers) + self.assertEqual(response.headers["Vary"], "Accept-Encoding") + + def test_vary_already_present(self): + response = self.fetch("/?vary=Accept-Language") + self.assert_compressed(response) + self.assertEqual( + [s.strip() for s in response.headers["Vary"].split(",")], + ["Accept-Language", "Accept-Encoding"], + ) + + def test_vary_already_present_multiple(self): + # Regression test for https://github.com/tornadoweb/tornado/issues/1670 + response = self.fetch("/?vary=Accept-Language&vary=Cookie") + self.assert_compressed(response) + self.assertEqual( + [s.strip() for s in response.headers["Vary"].split(",")], + ["Accept-Language", "Cookie", "Accept-Encoding"], + ) + + +class PathArgsInPrepareTest(WebTestCase): + class Handler(RequestHandler): + def prepare(self): + self.write(dict(args=self.path_args, kwargs=self.path_kwargs)) + + def get(self, path): + assert path == "foo" + self.finish() + + def get_handlers(self): + return [("/pos/(.*)", self.Handler), ("/kw/(?P.*)", self.Handler)] + + def test_pos(self): + response = self.fetch("/pos/foo") + response.rethrow() + data = json_decode(response.body) + self.assertEqual(data, {"args": ["foo"], "kwargs": {}}) + + def test_kw(self): + response = self.fetch("/kw/foo") + response.rethrow() + data = json_decode(response.body) + self.assertEqual(data, {"args": [], "kwargs": {"path": "foo"}}) + + +class ClearAllCookiesTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + self.clear_all_cookies() + self.write("ok") + + def test_clear_all_cookies(self): + response = self.fetch("/", headers={"Cookie": "foo=bar; baz=xyzzy"}) + set_cookies = sorted(response.headers.get_list("Set-Cookie")) + # Python 3.5 sends 'baz="";'; older versions use 'baz=;' + self.assertTrue(set_cookies[0].startswith('baz="";')) + self.assertTrue(set_cookies[1].startswith('foo="";')) + + +class PermissionError(Exception): + pass + + +class ExceptionHandlerTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + exc = self.get_argument("exc") + if exc == "http": + raise HTTPError(410, "no longer here") + elif exc == "zero": + 1 / 0 + elif exc == "permission": + raise PermissionError("not allowed") + + def write_error(self, status_code, **kwargs): + if "exc_info" in kwargs: + typ, value, tb = kwargs["exc_info"] + if isinstance(value, PermissionError): + self.set_status(403) + self.write("PermissionError") + return + RequestHandler.write_error(self, status_code, **kwargs) + + def log_exception(self, typ, value, tb): + if isinstance(value, PermissionError): + app_log.warning("custom logging for PermissionError: %s", value.args[0]) + else: + RequestHandler.log_exception(self, typ, value, tb) + + def test_http_error(self): + # HTTPErrors are logged as warnings with no stack trace. + # TODO: extend ExpectLog to test this more precisely + with ExpectLog(gen_log, ".*no longer here"): + response = self.fetch("/?exc=http") + self.assertEqual(response.code, 410) + + def test_unknown_error(self): + # Unknown errors are logged as errors with a stack trace. + with ExpectLog(app_log, "Uncaught exception"): + response = self.fetch("/?exc=zero") + self.assertEqual(response.code, 500) + + def test_known_error(self): + # log_exception can override logging behavior, and write_error + # can override the response. + with ExpectLog(app_log, "custom logging for PermissionError: not allowed"): + response = self.fetch("/?exc=permission") + self.assertEqual(response.code, 403) + + +class BuggyLoggingTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + 1 / 0 + + def log_exception(self, typ, value, tb): + 1 / 0 + + def test_buggy_log_exception(self): + # Something gets logged even though the application's + # logger is broken. + with ExpectLog(app_log, ".*"): + self.fetch("/") + + +class UIMethodUIModuleTest(SimpleHandlerTestCase): + """Test that UI methods and modules are created correctly and + associated with the handler. + """ + + class Handler(RequestHandler): + def get(self): + self.render("foo.html") + + def value(self): + return self.get_argument("value") + + def get_app_kwargs(self): + def my_ui_method(handler, x): + return f"In my_ui_method({x}) with handler value {handler.value()}." + + class MyModule(UIModule): + def render(self, x): + return "In MyModule({}) with handler value {}.".format( + x, + typing.cast(UIMethodUIModuleTest.Handler, self.handler).value(), + ) + + loader = DictLoader( + {"foo.html": "{{ my_ui_method(42) }} {% module MyModule(123) %}"} + ) + return dict( + template_loader=loader, + ui_methods={"my_ui_method": my_ui_method}, + ui_modules={"MyModule": MyModule}, + ) + + def tearDown(self): + super().tearDown() + # TODO: fix template loader caching so this isn't necessary. + RequestHandler._template_loaders.clear() + + def test_ui_method(self): + response = self.fetch("/?value=asdf") + self.assertEqual( + response.body, + b"In my_ui_method(42) with handler value asdf. " + b"In MyModule(123) with handler value asdf.", + ) + + +class GetArgumentErrorTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + try: + self.get_argument("foo") + self.write({}) + except MissingArgumentError as e: + self.write({"arg_name": e.arg_name, "log_message": e.log_message}) + + def test_catch_error(self): + response = self.fetch("/") + self.assertEqual( + json_decode(response.body), + {"arg_name": "foo", "log_message": "Missing argument foo"}, + ) + + +class SetLazyPropertiesTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def prepare(self): + self.current_user = "Ben" + self.locale = locale.get("en_US") + + def get_user_locale(self): + raise NotImplementedError() + + def get_current_user(self): + raise NotImplementedError() + + def get(self): + self.write(f"Hello {self.current_user} ({self.locale.code})") + + def test_set_properties(self): + # Ensure that current_user can be assigned to normally for apps + # that want to forgo the lazy get_current_user property + response = self.fetch("/") + self.assertEqual(response.body, b"Hello Ben (en_US)") + + +class GetCurrentUserTest(WebTestCase): + def get_app_kwargs(self): + class WithoutUserModule(UIModule): + def render(self): + return "" + + class WithUserModule(UIModule): + def render(self): + return str(self.current_user) + + loader = DictLoader( + { + "without_user.html": "", + "with_user.html": "{{ current_user }}", + "without_user_module.html": "{% module WithoutUserModule() %}", + "with_user_module.html": "{% module WithUserModule() %}", + } + ) + return dict( + template_loader=loader, + ui_modules={ + "WithUserModule": WithUserModule, + "WithoutUserModule": WithoutUserModule, + }, + ) + + def tearDown(self): + super().tearDown() + RequestHandler._template_loaders.clear() + + def get_handlers(self): + class CurrentUserHandler(RequestHandler): + def prepare(self): + self.has_loaded_current_user = False + + def get_current_user(self): + self.has_loaded_current_user = True + return "" + + class WithoutUserHandler(CurrentUserHandler): + def get(self): + self.render_string("without_user.html") + self.finish(str(self.has_loaded_current_user)) + + class WithUserHandler(CurrentUserHandler): + def get(self): + self.render_string("with_user.html") + self.finish(str(self.has_loaded_current_user)) + + class CurrentUserModuleHandler(CurrentUserHandler): + def get_template_namespace(self): + # If RequestHandler.get_template_namespace is called, then + # get_current_user is evaluated. Until #820 is fixed, this + # is a small hack to circumvent the issue. + return self.ui + + class WithoutUserModuleHandler(CurrentUserModuleHandler): + def get(self): + self.render_string("without_user_module.html") + self.finish(str(self.has_loaded_current_user)) + + class WithUserModuleHandler(CurrentUserModuleHandler): + def get(self): + self.render_string("with_user_module.html") + self.finish(str(self.has_loaded_current_user)) + + return [ + ("/without_user", WithoutUserHandler), + ("/with_user", WithUserHandler), + ("/without_user_module", WithoutUserModuleHandler), + ("/with_user_module", WithUserModuleHandler), + ] + + @unittest.skip("needs fix") + def test_get_current_user_is_lazy(self): + # TODO: Make this test pass. See #820. + response = self.fetch("/without_user") + self.assertEqual(response.body, b"False") + + def test_get_current_user_works(self): + response = self.fetch("/with_user") + self.assertEqual(response.body, b"True") + + def test_get_current_user_from_ui_module_is_lazy(self): + response = self.fetch("/without_user_module") + self.assertEqual(response.body, b"False") + + def test_get_current_user_from_ui_module_works(self): + response = self.fetch("/with_user_module") + self.assertEqual(response.body, b"True") + + +class UnimplementedHTTPMethodsTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + pass + + def test_unimplemented_standard_methods(self): + for method in ["HEAD", "GET", "DELETE", "OPTIONS"]: + response = self.fetch("/", method=method) + self.assertEqual(response.code, 405) + for method in ["POST", "PUT"]: + response = self.fetch("/", method=method, body=b"") + self.assertEqual(response.code, 405) + + +class UnimplementedNonStandardMethodsTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def other(self): + # Even though this method exists, it won't get called automatically + # because it is not in SUPPORTED_METHODS. + self.write("other") + + def test_unimplemented_patch(self): + # PATCH is recently standardized; Tornado supports it by default + # but wsgiref.validate doesn't like it. + response = self.fetch("/", method="PATCH", body=b"") + self.assertEqual(response.code, 405) + + def test_unimplemented_other(self): + response = self.fetch("/", method="OTHER", allow_nonstandard_methods=True) + self.assertEqual(response.code, 405) + + +class AllHTTPMethodsTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def method(self): + assert self.request.method is not None + self.write(self.request.method) + + get = delete = options = post = put = method # type: ignore + + def test_standard_methods(self): + response = self.fetch("/", method="HEAD") + self.assertEqual(response.body, b"") + for method in ["GET", "DELETE", "OPTIONS"]: + response = self.fetch("/", method=method) + self.assertEqual(response.body, utf8(method)) + for method in ["POST", "PUT"]: + response = self.fetch("/", method=method, body=b"") + self.assertEqual(response.body, utf8(method)) + + +class PatchMethodTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ( # type: ignore + "OTHER", + ) + + def patch(self): + self.write("patch") + + def other(self): + self.write("other") + + def test_patch(self): + response = self.fetch("/", method="PATCH", body=b"") + self.assertEqual(response.body, b"patch") + + def test_other(self): + response = self.fetch("/", method="OTHER", allow_nonstandard_methods=True) + self.assertEqual(response.body, b"other") + + +class FinishInPrepareTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def prepare(self): + self.finish("done") + + def get(self): + # It's difficult to assert for certain that a method did not + # or will not be called in an asynchronous context, but this + # will be logged noisily if it is reached. + raise Exception("should not reach this method") + + def test_finish_in_prepare(self): + response = self.fetch("/") + self.assertEqual(response.body, b"done") + + +class Default404Test(WebTestCase): + def get_handlers(self): + # If there are no handlers at all a default redirect handler gets added. + return [("/foo", RequestHandler)] + + def test_404(self): + response = self.fetch("/") + self.assertEqual(response.code, 404) + self.assertEqual( + response.body, + b"404: Not Found" + b"404: Not Found", + ) + + +class Custom404Test(WebTestCase): + def get_handlers(self): + return [("/foo", RequestHandler)] + + def get_app_kwargs(self): + class Custom404Handler(RequestHandler): + def get(self): + self.set_status(404) + self.write("custom 404 response") + + return dict(default_handler_class=Custom404Handler) + + def test_404(self): + response = self.fetch("/") + self.assertEqual(response.code, 404) + self.assertEqual(response.body, b"custom 404 response") + + +class DefaultHandlerArgumentsTest(WebTestCase): + def get_handlers(self): + return [("/foo", RequestHandler)] + + def get_app_kwargs(self): + return dict( + default_handler_class=ErrorHandler, + default_handler_args=dict(status_code=403), + ) + + def test_403(self): + response = self.fetch("/") + self.assertEqual(response.code, 403) + + +class HandlerByNameTest(WebTestCase): + def get_handlers(self): + # All three are equivalent. + return [ + ("/hello1", HelloHandler), + ("/hello2", "tornado.test.web_test.HelloHandler"), + url("/hello3", "tornado.test.web_test.HelloHandler"), + ] + + def test_handler_by_name(self): + resp = self.fetch("/hello1") + self.assertEqual(resp.body, b"hello") + resp = self.fetch("/hello2") + self.assertEqual(resp.body, b"hello") + resp = self.fetch("/hello3") + self.assertEqual(resp.body, b"hello") + + +class StreamingRequestBodyTest(WebTestCase): + def get_handlers(self): + @stream_request_body + class StreamingBodyHandler(RequestHandler): + def initialize(self, test): + self.test = test + + def prepare(self): + self.test.prepared.set_result(None) + + def data_received(self, data): + self.test.data.set_result(data) + + def get(self): + self.test.finished.set_result(None) + self.write({}) + + @stream_request_body + class EarlyReturnHandler(RequestHandler): + def prepare(self): + # If we finish the response in prepare, it won't continue to + # the (non-existent) data_received. + raise HTTPError(401) + + @stream_request_body + class CloseDetectionHandler(RequestHandler): + def initialize(self, test): + self.test = test + + def on_connection_close(self): + super().on_connection_close() + self.test.close_future.set_result(None) + + return [ + ("/stream_body", StreamingBodyHandler, dict(test=self)), + ("/early_return", EarlyReturnHandler), + ("/close_detection", CloseDetectionHandler, dict(test=self)), + ] + + def connect(self, url, connection_close): + # Use a raw connection so we can control the sending of data. + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) + s.connect(("127.0.0.1", self.get_http_port())) + stream = IOStream(s) + stream.write(b"GET " + url + b" HTTP/1.1\r\nHost: 127.0.0.1\r\n") + if connection_close: + stream.write(b"Connection: close\r\n") + stream.write(b"Transfer-Encoding: chunked\r\n\r\n") + return stream + + @gen_test + def test_streaming_body(self): + self.prepared = Future() # type: Future[None] + self.data = Future() # type: Future[bytes] + self.finished = Future() # type: Future[None] + + stream = self.connect(b"/stream_body", connection_close=True) + yield self.prepared + stream.write(b"4\r\nasdf\r\n") + # Ensure the first chunk is received before we send the second. + data = yield self.data + self.assertEqual(data, b"asdf") + self.data = Future() + stream.write(b"4\r\nqwer\r\n") + data = yield self.data + self.assertEqual(data, b"qwer") + stream.write(b"0\r\n\r\n") + yield self.finished + data = yield stream.read_until_close() + # This would ideally use an HTTP1Connection to read the response. + self.assertTrue(data.endswith(b"{}")) + stream.close() + + @gen_test + def test_early_return(self): + stream = self.connect(b"/early_return", connection_close=False) + data = yield stream.read_until_close() + self.assertTrue(data.startswith(b"HTTP/1.1 401")) + + @gen_test + def test_early_return_with_data(self): + stream = self.connect(b"/early_return", connection_close=False) + stream.write(b"4\r\nasdf\r\n") + data = yield stream.read_until_close() + self.assertTrue(data.startswith(b"HTTP/1.1 401")) + + @gen_test + def test_close_during_upload(self): + self.close_future = Future() # type: Future[None] + stream = self.connect(b"/close_detection", connection_close=False) + stream.close() + yield self.close_future + + +# Each method in this handler returns a yieldable object and yields to the +# IOLoop so the future is not immediately ready. Ensure that the +# yieldables are respected and no method is called before the previous +# one has completed. +@stream_request_body +class BaseFlowControlHandler(RequestHandler): + def initialize(self, test): + self.test = test + self.method = None + self.methods = [] # type: typing.List[str] + + @contextlib.contextmanager + def in_method(self, method): + if self.method is not None: + self.test.fail(f"entered method {method} while in {self.method}") + self.method = method + self.methods.append(method) + try: + yield + finally: + self.method = None + + @gen.coroutine + def prepare(self): + # Note that asynchronous prepare() does not block data_received, + # so we don't use in_method here. + self.methods.append("prepare") + yield gen.moment + + @gen.coroutine + def post(self): + with self.in_method("post"): + yield gen.moment + self.write(dict(methods=self.methods)) + + +class BaseStreamingRequestFlowControlTest: + def get_httpserver_options(self): + # Use a small chunk size so flow control is relevant even though + # all the data arrives at once. + return dict(chunk_size=10, decompress_request=True) + + def get_http_client(self): + # simple_httpclient only: curl doesn't support body_producer. + return SimpleAsyncHTTPClient() + + # Test all the slightly different code paths for fixed, chunked, etc bodies. + def test_flow_control_fixed_body(self: typing.Any): + response = self.fetch("/", body="abcdefghijklmnopqrstuvwxyz", method="POST") + response.rethrow() + self.assertEqual( + json_decode(response.body), + dict( + methods=[ + "prepare", + "data_received", + "data_received", + "data_received", + "post", + ] + ), + ) + + def test_flow_control_chunked_body(self: typing.Any): + chunks = [b"abcd", b"efgh", b"ijkl"] + + @gen.coroutine + def body_producer(write): + for i in chunks: + yield write(i) + + response = self.fetch("/", body_producer=body_producer, method="POST") + response.rethrow() + self.assertEqual( + json_decode(response.body), + dict( + methods=[ + "prepare", + "data_received", + "data_received", + "data_received", + "post", + ] + ), + ) + + def test_flow_control_compressed_body(self: typing.Any): + bytesio = BytesIO() + gzip_file = gzip.GzipFile(mode="w", fileobj=bytesio) + gzip_file.write(b"abcdefghijklmnopqrstuvwxyz") + gzip_file.close() + compressed_body = bytesio.getvalue() + response = self.fetch( + "/", + body=compressed_body, + method="POST", + headers={"Content-Encoding": "gzip"}, + ) + response.rethrow() + self.assertEqual( + json_decode(response.body), + dict( + methods=[ + "prepare", + "data_received", + "data_received", + "data_received", + "post", + ] + ), + ) + + +class DecoratedStreamingRequestFlowControlTest( + BaseStreamingRequestFlowControlTest, WebTestCase +): + def get_handlers(self): + class DecoratedFlowControlHandler(BaseFlowControlHandler): + @gen.coroutine + def data_received(self, data): + with self.in_method("data_received"): + yield gen.moment + + return [("/", DecoratedFlowControlHandler, dict(test=self))] + + +class NativeStreamingRequestFlowControlTest( + BaseStreamingRequestFlowControlTest, WebTestCase +): + def get_handlers(self): + class NativeFlowControlHandler(BaseFlowControlHandler): + async def data_received(self, data): + with self.in_method("data_received"): + import asyncio + + await asyncio.sleep(0) + + return [("/", NativeFlowControlHandler, dict(test=self))] + + +class IncorrectContentLengthTest(SimpleHandlerTestCase): + def get_handlers(self): + test = self + self.server_error = None + + # Manually set a content-length that doesn't match the actual content. + class TooHigh(RequestHandler): + def get(self): + self.set_header("Content-Length", "42") + try: + self.finish("ok") + except Exception as e: + test.server_error = e + raise + + class TooLow(RequestHandler): + def get(self): + self.set_header("Content-Length", "2") + try: + self.finish("hello") + except Exception as e: + test.server_error = e + raise + + return [("/high", TooHigh), ("/low", TooLow)] + + def test_content_length_too_high(self): + # When the content-length is too high, the connection is simply + # closed without completing the response. An error is logged on + # the server. + with ExpectLog(app_log, "(Uncaught exception|Exception in callback)"): + with ExpectLog( + gen_log, + "(Cannot send error response after headers written" + "|Failed to flush partial response)", + ): + with self.assertRaises(HTTPClientError): + self.fetch("/high", raise_error=True) + self.assertEqual( + str(self.server_error), "Tried to write 40 bytes less than Content-Length" + ) + + def test_content_length_too_low(self): + # When the content-length is too low, the connection is closed + # without writing the last chunk, so the client never sees the request + # complete (which would be a framing error). + with ExpectLog(app_log, "(Uncaught exception|Exception in callback)"): + with ExpectLog( + gen_log, + "(Cannot send error response after headers written" + "|Failed to flush partial response)", + ): + with self.assertRaises(HTTPClientError): + self.fetch("/low", raise_error=True) + self.assertEqual( + str(self.server_error), "Tried to write more data than Content-Length" + ) + + +class ClientCloseTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + if self.request.version.startswith("HTTP/1"): + # Simulate a connection closed by the client during + # request processing. The client will see an error, but the + # server should respond gracefully (without logging errors + # because we were unable to write out as many bytes as + # Content-Length said we would) + self.request.connection.stream.close() # type: ignore + self.write("hello") + else: + # TODO: add a HTTP2-compatible version of this test. + self.write("requires HTTP/1.x") + + def test_client_close(self): + with self.assertRaises((HTTPClientError, unittest.SkipTest)): # type: ignore + response = self.fetch("/", raise_error=True) + if response.body == b"requires HTTP/1.x": + self.skipTest("requires HTTP/1.x") + self.assertEqual(response.code, 599) + + +class SignedValueTest(unittest.TestCase): + SECRET = "It's a secret to everybody" + SECRET_DICT = {0: "asdfbasdf", 1: "12312312", 2: "2342342"} + + def past(self): + return self.present() - 86400 * 32 + + def present(self): + return 1300000000 + + def test_known_values(self): + signed_v1 = create_signed_value( + SignedValueTest.SECRET, "key", "value", version=1, clock=self.present + ) + self.assertEqual( + signed_v1, b"dmFsdWU=|1300000000|31c934969f53e48164c50768b40cbd7e2daaaa4f" + ) + + signed_v2 = create_signed_value( + SignedValueTest.SECRET, "key", "value", version=2, clock=self.present + ) + self.assertEqual( + signed_v2, + b"2|1:0|10:1300000000|3:key|8:dmFsdWU=|" + b"3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e152", + ) + + signed_default = create_signed_value( + SignedValueTest.SECRET, "key", "value", clock=self.present + ) + self.assertEqual(signed_default, signed_v2) + + decoded_v1 = decode_signed_value( + SignedValueTest.SECRET, "key", signed_v1, min_version=1, clock=self.present + ) + self.assertEqual(decoded_v1, b"value") + + decoded_v2 = decode_signed_value( + SignedValueTest.SECRET, "key", signed_v2, min_version=2, clock=self.present + ) + self.assertEqual(decoded_v2, b"value") + + def test_name_swap(self): + signed1 = create_signed_value( + SignedValueTest.SECRET, "key1", "value", clock=self.present + ) + signed2 = create_signed_value( + SignedValueTest.SECRET, "key2", "value", clock=self.present + ) + # Try decoding each string with the other's "name" + decoded1 = decode_signed_value( + SignedValueTest.SECRET, "key2", signed1, clock=self.present + ) + self.assertIsNone(decoded1) + decoded2 = decode_signed_value( + SignedValueTest.SECRET, "key1", signed2, clock=self.present + ) + self.assertIsNone(decoded2) + + def test_expired(self): + signed = create_signed_value( + SignedValueTest.SECRET, "key1", "value", clock=self.past + ) + decoded_past = decode_signed_value( + SignedValueTest.SECRET, "key1", signed, clock=self.past + ) + self.assertEqual(decoded_past, b"value") + decoded_present = decode_signed_value( + SignedValueTest.SECRET, "key1", signed, clock=self.present + ) + self.assertIsNone(decoded_present) + + def test_payload_tampering(self): + # These cookies are variants of the one in test_known_values. + sig = "3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e152" + + def validate(prefix): + return b"value" == decode_signed_value( + SignedValueTest.SECRET, "key", prefix + sig, clock=self.present + ) + + self.assertTrue(validate("2|1:0|10:1300000000|3:key|8:dmFsdWU=|")) + # Change key version + self.assertFalse(validate("2|1:1|10:1300000000|3:key|8:dmFsdWU=|")) + # length mismatch (field too short) + self.assertFalse(validate("2|1:0|10:130000000|3:key|8:dmFsdWU=|")) + # length mismatch (field too long) + self.assertFalse(validate("2|1:0|10:1300000000|3:keey|8:dmFsdWU=|")) + + def test_signature_tampering(self): + prefix = "2|1:0|10:1300000000|3:key|8:dmFsdWU=|" + + def validate(sig): + return b"value" == decode_signed_value( + SignedValueTest.SECRET, "key", prefix + sig, clock=self.present + ) + + self.assertTrue( + validate("3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e152") + ) + # All zeros + self.assertFalse(validate("0" * 32)) + # Change one character + self.assertFalse( + validate("4d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e152") + ) + # Change another character + self.assertFalse( + validate("3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e153") + ) + # Truncate + self.assertFalse( + validate("3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e15") + ) + # Lengthen + self.assertFalse( + validate( + "3d4e60b996ff9c5d5788e333a0cba6f238a22c6c0f94788870e1a9ecd482e1538" + ) + ) + + def test_non_ascii(self): + value = b"\xe9" + signed = create_signed_value( + SignedValueTest.SECRET, "key", value, clock=self.present + ) + decoded = decode_signed_value( + SignedValueTest.SECRET, "key", signed, clock=self.present + ) + self.assertEqual(value, decoded) + + def test_key_versioning_read_write_default_key(self): + value = b"\xe9" + signed = create_signed_value( + SignedValueTest.SECRET_DICT, "key", value, clock=self.present, key_version=0 + ) + decoded = decode_signed_value( + SignedValueTest.SECRET_DICT, "key", signed, clock=self.present + ) + self.assertEqual(value, decoded) + + def test_key_versioning_read_write_non_default_key(self): + value = b"\xe9" + signed = create_signed_value( + SignedValueTest.SECRET_DICT, "key", value, clock=self.present, key_version=1 + ) + decoded = decode_signed_value( + SignedValueTest.SECRET_DICT, "key", signed, clock=self.present + ) + self.assertEqual(value, decoded) + + def test_key_versioning_invalid_key(self): + value = b"\xe9" + signed = create_signed_value( + SignedValueTest.SECRET_DICT, "key", value, clock=self.present, key_version=0 + ) + newkeys = SignedValueTest.SECRET_DICT.copy() + newkeys.pop(0) + decoded = decode_signed_value(newkeys, "key", signed, clock=self.present) + self.assertIsNone(decoded) + + def test_key_version_retrieval(self): + value = b"\xe9" + signed = create_signed_value( + SignedValueTest.SECRET_DICT, "key", value, clock=self.present, key_version=1 + ) + key_version = get_signature_key_version(signed) + self.assertEqual(1, key_version) + + +class XSRFTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + version = int(self.get_argument("version", "2")) + # This would be a bad idea in a real app, but in this test + # it's fine. + self.settings["xsrf_cookie_version"] = version + self.write(self.xsrf_token) + + def post(self): + self.write("ok") + + def get_app_kwargs(self): + return dict(xsrf_cookies=True) + + def setUp(self): + super().setUp() + self.xsrf_token = self.get_token() + + def get_token(self, old_token=None, version=None): + if old_token is not None: + headers = self.cookie_headers(old_token) + else: + headers = None + response = self.fetch( + "/" if version is None else ("/?version=%d" % version), headers=headers + ) + response.rethrow() + return native_str(response.body) + + def cookie_headers(self, token=None): + if token is None: + token = self.xsrf_token + return {"Cookie": "_xsrf=" + token} + + def test_xsrf_fail_no_token(self): + with ExpectLog(gen_log, ".*'_xsrf' argument missing"): + response = self.fetch("/", method="POST", body=b"") + self.assertEqual(response.code, 403) + + def test_xsrf_fail_body_no_cookie(self): + with ExpectLog(gen_log, ".*XSRF cookie does not match POST"): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + ) + self.assertEqual(response.code, 403) + + def test_xsrf_fail_argument_invalid_format(self): + with ExpectLog(gen_log, ".*'_xsrf' argument has invalid format"): + response = self.fetch( + "/", + method="POST", + headers=self.cookie_headers(), + body=urllib.parse.urlencode(dict(_xsrf="3|")), + ) + self.assertEqual(response.code, 403) + + def test_xsrf_fail_cookie_invalid_format(self): + with ExpectLog(gen_log, ".*XSRF cookie does not match POST"): + response = self.fetch( + "/", + method="POST", + headers=self.cookie_headers(token="3|"), + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + ) + self.assertEqual(response.code, 403) + + def test_xsrf_fail_cookie_no_body(self): + with ExpectLog(gen_log, ".*'_xsrf' argument missing"): + response = self.fetch( + "/", method="POST", body=b"", headers=self.cookie_headers() + ) + self.assertEqual(response.code, 403) + + def test_xsrf_success_short_token(self): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf="deadbeef")), + headers=self.cookie_headers(token="deadbeef"), + ) + self.assertEqual(response.code, 200) + + def test_xsrf_success_non_hex_token(self): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf="xoxo")), + headers=self.cookie_headers(token="xoxo"), + ) + self.assertEqual(response.code, 200) + + def test_xsrf_success_post_body(self): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + headers=self.cookie_headers(), + ) + self.assertEqual(response.code, 200) + + def test_xsrf_success_query_string(self): + response = self.fetch( + "/?" + urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + method="POST", + body=b"", + headers=self.cookie_headers(), + ) + self.assertEqual(response.code, 200) + + def test_xsrf_success_header(self): + response = self.fetch( + "/", + method="POST", + body=b"", + headers=dict( + {"X-Xsrftoken": self.xsrf_token}, # type: ignore + **self.cookie_headers(), + ), + ) + self.assertEqual(response.code, 200) + + def test_distinct_tokens(self): + # Every request gets a distinct token. + NUM_TOKENS = 10 + tokens = set() + for i in range(NUM_TOKENS): + tokens.add(self.get_token()) + self.assertEqual(len(tokens), NUM_TOKENS) + + def test_cross_user(self): + token2 = self.get_token() + # Each token can be used to authenticate its own request. + for token in (self.xsrf_token, token2): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=token)), + headers=self.cookie_headers(token), + ) + self.assertEqual(response.code, 200) + # Sending one in the cookie and the other in the body is not allowed. + for cookie_token, body_token in ( + (self.xsrf_token, token2), + (token2, self.xsrf_token), + ): + with ExpectLog(gen_log, ".*XSRF cookie does not match POST"): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=body_token)), + headers=self.cookie_headers(cookie_token), + ) + self.assertEqual(response.code, 403) + + def test_refresh_token(self): + token = self.xsrf_token + tokens_seen = {token} + # A user's token is stable over time. Refreshing the page in one tab + # might update the cookie while an older tab still has the old cookie + # in its DOM. Simulate this scenario by passing a constant token + # in the body and re-querying for the token. + for i in range(5): + token = self.get_token(token) + # Tokens are encoded uniquely each time + tokens_seen.add(token) + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + headers=self.cookie_headers(token), + ) + self.assertEqual(response.code, 200) + self.assertEqual(len(tokens_seen), 6) + + def test_versioning(self): + # Version 1 still produces distinct tokens per request. + self.assertNotEqual(self.get_token(version=1), self.get_token(version=1)) + + # Refreshed v1 tokens are all identical. + v1_token = self.get_token(version=1) + for i in range(5): + self.assertEqual(self.get_token(v1_token, version=1), v1_token) + + # Upgrade to a v2 version of the same token + v2_token = self.get_token(v1_token) + self.assertNotEqual(v1_token, v2_token) + # Each v1 token can map to many v2 tokens. + self.assertNotEqual(v2_token, self.get_token(v1_token)) + + # The tokens are cross-compatible. + for cookie_token, body_token in ((v1_token, v2_token), (v2_token, v1_token)): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=body_token)), + headers=self.cookie_headers(cookie_token), + ) + self.assertEqual(response.code, 200) + + +# A subset of the previous test with a different cookie name +class XSRFCookieNameTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + self.write(self.xsrf_token) + + def post(self): + self.write("ok") + + def get_app_kwargs(self): + return dict( + xsrf_cookies=True, + xsrf_cookie_name="__Host-xsrf", + xsrf_cookie_kwargs={"secure": True}, + ) + + def setUp(self): + super().setUp() + self.xsrf_token = self.get_token() + + def get_token(self, old_token=None): + if old_token is not None: + headers = self.cookie_headers(old_token) + else: + headers = None + response = self.fetch("/", headers=headers) + response.rethrow() + return native_str(response.body) + + def cookie_headers(self, token=None): + if token is None: + token = self.xsrf_token + return {"Cookie": "__Host-xsrf=" + token} + + def test_xsrf_fail_no_token(self): + with ExpectLog(gen_log, ".*'_xsrf' argument missing"): + response = self.fetch("/", method="POST", body=b"") + self.assertEqual(response.code, 403) + + def test_xsrf_fail_body_no_cookie(self): + with ExpectLog(gen_log, ".*XSRF cookie does not match POST"): + response = self.fetch( + "/", + method="POST", + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + ) + self.assertEqual(response.code, 403) + + def test_xsrf_success_post_body(self): + response = self.fetch( + "/", + method="POST", + # Note that renaming the cookie doesn't rename the POST param + body=urllib.parse.urlencode(dict(_xsrf=self.xsrf_token)), + headers=self.cookie_headers(), + ) + self.assertEqual(response.code, 200) + + +class XSRFCookieKwargsTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + self.write(self.xsrf_token) + + def get_app_kwargs(self): + return dict( + xsrf_cookies=True, xsrf_cookie_kwargs=dict(httponly=True, expires_days=2) + ) + + def test_xsrf_httponly(self): + response = self.fetch("/") + self.assertIn("httponly;", response.headers["Set-Cookie"].lower()) + self.assertIn("expires=", response.headers["Set-Cookie"].lower()) + header = response.headers.get("Set-Cookie") + assert header is not None + match = re.match(".*; expires=(?P.+);.*", header) + assert match is not None + + expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( + days=2 + ) + header_expires = email.utils.parsedate_to_datetime(match.groupdict()["expires"]) + if header_expires.tzinfo is None: + header_expires = header_expires.replace(tzinfo=datetime.timezone.utc) + self.assertTrue(abs((expires - header_expires).total_seconds()) < 10) + + +class FinishExceptionTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + self.set_status(401) + self.set_header("WWW-Authenticate", 'Basic realm="something"') + if self.get_argument("finish_value", ""): + raise Finish("authentication required") + else: + self.write("authentication required") + raise Finish() + + def test_finish_exception(self): + for u in ["/", "/?finish_value=1"]: + response = self.fetch(u) + self.assertEqual(response.code, 401) + self.assertEqual( + 'Basic realm="something"', response.headers.get("WWW-Authenticate") + ) + self.assertEqual(b"authentication required", response.body) + + +class DecoratorTest(WebTestCase): + def get_handlers(self): + class RemoveSlashHandler(RequestHandler): + @removeslash + def get(self): + pass + + class AddSlashHandler(RequestHandler): + @addslash + def get(self): + pass + + return [("/removeslash/", RemoveSlashHandler), ("/addslash", AddSlashHandler)] + + def test_removeslash(self): + response = self.fetch("/removeslash/", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/removeslash") + + response = self.fetch("/removeslash/?foo=bar", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/removeslash?foo=bar") + + def test_addslash(self): + response = self.fetch("/addslash", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/addslash/") + + response = self.fetch("/addslash?foo=bar", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/addslash/?foo=bar") + + +class CacheTest(WebTestCase): + def get_handlers(self): + class EtagHandler(RequestHandler): + def get(self, computed_etag): + self.write(computed_etag) + + def compute_etag(self): + return self._write_buffer[0] + + return [("/etag/(.*)", EtagHandler)] + + def test_wildcard_etag(self): + computed_etag = '"xyzzy"' + etags = "*" + self._test_etag(computed_etag, etags, 304) + + def test_strong_etag_match(self): + computed_etag = '"xyzzy"' + etags = '"xyzzy"' + self._test_etag(computed_etag, etags, 304) + + def test_multiple_strong_etag_match(self): + computed_etag = '"xyzzy1"' + etags = '"xyzzy1", "xyzzy2"' + self._test_etag(computed_etag, etags, 304) + + def test_strong_etag_not_match(self): + computed_etag = '"xyzzy"' + etags = '"xyzzy1"' + self._test_etag(computed_etag, etags, 200) + + def test_multiple_strong_etag_not_match(self): + computed_etag = '"xyzzy"' + etags = '"xyzzy1", "xyzzy2"' + self._test_etag(computed_etag, etags, 200) + + def test_weak_etag_match(self): + computed_etag = '"xyzzy1"' + etags = 'W/"xyzzy1"' + self._test_etag(computed_etag, etags, 304) + + def test_multiple_weak_etag_match(self): + computed_etag = '"xyzzy2"' + etags = 'W/"xyzzy1", W/"xyzzy2"' + self._test_etag(computed_etag, etags, 304) + + def test_weak_etag_not_match(self): + computed_etag = '"xyzzy2"' + etags = 'W/"xyzzy1"' + self._test_etag(computed_etag, etags, 200) + + def test_multiple_weak_etag_not_match(self): + computed_etag = '"xyzzy3"' + etags = 'W/"xyzzy1", W/"xyzzy2"' + self._test_etag(computed_etag, etags, 200) + + def _test_etag(self, computed_etag, etags, status_code): + response = self.fetch( + "/etag/" + computed_etag, headers={"If-None-Match": etags} + ) + self.assertEqual(response.code, status_code) + + +class RequestSummaryTest(SimpleHandlerTestCase): + class Handler(RequestHandler): + def get(self): + # remote_ip is optional, although it's set by + # both HTTPServer and WSGIAdapter. + # Clobber it to make sure it doesn't break logging. + self.request.remote_ip = None + self.finish(self._request_summary()) + + def test_missing_remote_ip(self): + resp = self.fetch("/") + self.assertEqual(resp.body, b"GET / (None)") + + +class HTTPErrorTest(unittest.TestCase): + def test_copy(self): + e = HTTPError(403, reason="Go away") + e2 = copy.copy(e) + self.assertIsNot(e, e2) + self.assertEqual(e.status_code, e2.status_code) + self.assertEqual(e.reason, e2.reason) + + +class ApplicationTest(AsyncTestCase): + def test_listen(self): + app = Application([]) + server = app.listen(0, address="127.0.0.1") + server.stop() + + +class URLSpecReverseTest(unittest.TestCase): + def test_reverse(self): + self.assertEqual("/favicon.ico", url(r"/favicon\.ico", None).reverse()) + self.assertEqual("/favicon.ico", url(r"^/favicon\.ico$", None).reverse()) + + def test_non_reversible(self): + # URLSpecs are non-reversible if they include non-constant + # regex features outside capturing groups. Currently, this is + # only strictly enforced for backslash-escaped character + # classes. + paths = [r"^/api/v\d+/foo/(\w+)$"] + for path in paths: + # A URLSpec can still be created even if it cannot be reversed. + url_spec = url(path, None) + try: + result = url_spec.reverse() + self.fail( + "did not get expected exception when reversing %s. " + "result: %s" % (path, result) + ) + except ValueError: + pass + + def test_reverse_arguments(self): + self.assertEqual( + "/api/v1/foo/bar", url(r"^/api/v1/foo/(\w+)$", None).reverse("bar") + ) + self.assertEqual( + "/api.v1/foo/5/icon.png", + url(r"/api\.v1/foo/([0-9]+)/icon\.png", None).reverse(5), + ) + + +class RedirectHandlerTest(WebTestCase): + def get_handlers(self): + return [ + ("/src", WebRedirectHandler, {"url": "/dst"}), + ("/src2", WebRedirectHandler, {"url": "/dst2?foo=bar"}), + (r"/(.*?)/(.*?)/(.*)", WebRedirectHandler, {"url": "/{1}/{0}/{2}"}), + ] + + def test_basic_redirect(self): + response = self.fetch("/src", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/dst") + + def test_redirect_with_argument(self): + response = self.fetch("/src?foo=bar", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/dst?foo=bar") + + def test_redirect_with_appending_argument(self): + response = self.fetch("/src2?foo2=bar2", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/dst2?foo=bar&foo2=bar2") + + def test_redirect_pattern(self): + response = self.fetch("/a/b/c", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers["Location"], "/b/a/c") + + +class AcceptLanguageTest(WebTestCase): + """Test evaluation of Accept-Language header""" + + def get_handlers(self): + locale.load_gettext_translations( + os.path.join(os.path.dirname(__file__), "gettext_translations"), + "tornado_test", + ) + + class AcceptLanguageHandler(RequestHandler): + def get(self): + self.set_header( + "Content-Language", self.get_browser_locale().code.replace("_", "-") + ) + self.finish(b"") + + return [ + ("/", AcceptLanguageHandler), + ] + + def test_accept_language(self): + response = self.fetch("/", headers={"Accept-Language": "fr-FR;q=0.9"}) + self.assertEqual(response.headers["Content-Language"], "fr-FR") + + response = self.fetch("/", headers={"Accept-Language": "fr-FR; q=0.9"}) + self.assertEqual(response.headers["Content-Language"], "fr-FR") + + def test_accept_language_ignore(self): + response = self.fetch("/", headers={"Accept-Language": "fr-FR;q=0"}) + self.assertEqual(response.headers["Content-Language"], "en-US") + + def test_accept_language_invalid(self): + response = self.fetch("/", headers={"Accept-Language": "fr-FR;q=-1"}) + self.assertEqual(response.headers["Content-Language"], "en-US") diff --git a/python/user_packages/Python313/site-packages/tornado/test/websocket_test.py b/python/user_packages/Python313/site-packages/tornado/test/websocket_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9e4891addef8a797d69e818d986e24bd9db90b39 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/websocket_test.py @@ -0,0 +1,989 @@ +import asyncio +import contextlib +import datetime +import functools +import socket +import traceback +import typing +import unittest + +from tornado.concurrent import Future +from tornado import gen +from tornado.httpclient import HTTPError, HTTPRequest +from tornado.locks import Event +from tornado.log import gen_log, app_log +from tornado.netutil import Resolver +from tornado.simple_httpclient import SimpleAsyncHTTPClient +from tornado.template import DictLoader +from tornado.test.util import abstract_base_test, ignore_deprecation +from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog +from tornado.web import Application, RequestHandler + +try: + import tornado.websocket # noqa: F401 + from tornado.util import _websocket_mask_python +except ImportError: + # The unittest module presents misleading errors on ImportError + # (it acts as if websocket_test could not be found, hiding the underlying + # error). If we get an ImportError here (which could happen due to + # TORNADO_EXTENSION=1), print some extra information before failing. + traceback.print_exc() + raise + +from tornado.websocket import ( + WebSocketHandler, + websocket_connect, + WebSocketError, + WebSocketClosedError, +) + +try: + from tornado import speedups +except ImportError: + speedups = None # type: ignore + + +class TestWebSocketHandler(WebSocketHandler): + """Base class for testing handlers that exposes the on_close event. + + This allows for tests to see the close code and reason on the + server side. + + """ + + def initialize(self, close_future=None, compression_options=None): + self.close_future = close_future + self.compression_options = compression_options + + def get_compression_options(self): + return self.compression_options + + def on_close(self): + if self.close_future is not None: + self.close_future.set_result((self.close_code, self.close_reason)) + + +class EchoHandler(TestWebSocketHandler): + @gen.coroutine + def on_message(self, message): + try: + yield self.write_message(message, isinstance(message, bytes)) + except asyncio.CancelledError: + pass + except WebSocketClosedError: + pass + + +class ErrorInOnMessageHandler(TestWebSocketHandler): + def on_message(self, message): + 1 / 0 + + +class HeaderHandler(TestWebSocketHandler): + def open(self): + methods_to_test = [ + functools.partial(self.write, "This should not work"), + functools.partial(self.redirect, "http://localhost/elsewhere"), + functools.partial(self.set_header, "X-Test", ""), + functools.partial(self.set_cookie, "Chocolate", "Chip"), + functools.partial(self.set_status, 503), + self.flush, + self.finish, + ] + for method in methods_to_test: + try: + # In a websocket context, many RequestHandler methods + # raise RuntimeErrors. + method() # type: ignore + raise Exception("did not get expected exception") + except RuntimeError: + pass + self.write_message(self.request.headers.get("X-Test", "")) + + +class HeaderEchoHandler(TestWebSocketHandler): + def set_default_headers(self): + self.set_header("X-Extra-Response-Header", "Extra-Response-Value") + + def prepare(self): + for k, v in self.request.headers.get_all(): + if k.lower().startswith("x-test"): + self.set_header(k, v) + + +class NonWebSocketHandler(RequestHandler): + def get(self): + self.write("ok") + + +class RedirectHandler(RequestHandler): + def get(self): + self.redirect("/echo") + + +class CloseReasonHandler(TestWebSocketHandler): + def open(self): + self.on_close_called = False + self.close(1001, "goodbye") + + +class AsyncPrepareHandler(TestWebSocketHandler): + @gen.coroutine + def prepare(self): + yield gen.moment + + def on_message(self, message): + self.write_message(message) + + +class PathArgsHandler(TestWebSocketHandler): + def open(self, arg): + self.write_message(arg) + + +class CoroutineOnMessageHandler(TestWebSocketHandler): + def initialize(self, **kwargs): + super().initialize(**kwargs) + self.sleeping = 0 + + @gen.coroutine + def on_message(self, message): + if self.sleeping > 0: + self.write_message("another coroutine is already sleeping") + self.sleeping += 1 + yield gen.sleep(0.01) + self.sleeping -= 1 + self.write_message(message) + + +class RenderMessageHandler(TestWebSocketHandler): + def on_message(self, message): + self.write_message(self.render_string("message.html", message=message)) + + +class SubprotocolHandler(TestWebSocketHandler): + def initialize(self, **kwargs): + super().initialize(**kwargs) + self.select_subprotocol_called = False + + def select_subprotocol(self, subprotocols): + if self.select_subprotocol_called: + raise Exception("select_subprotocol called twice") + self.select_subprotocol_called = True + if "goodproto" in subprotocols: + return "goodproto" + return None + + def open(self): + if not self.select_subprotocol_called: + raise Exception("select_subprotocol not called") + self.write_message("subprotocol=%s" % self.selected_subprotocol) + + +class OpenCoroutineHandler(TestWebSocketHandler): + def initialize(self, test, **kwargs): + super().initialize(**kwargs) + self.test = test + self.open_finished = False + + @gen.coroutine + def open(self): + yield self.test.message_sent.wait() + yield gen.sleep(0.010) + self.open_finished = True + + def on_message(self, message): + if not self.open_finished: + raise Exception("on_message called before open finished") + self.write_message("ok") + + +class ErrorInOpenHandler(TestWebSocketHandler): + def open(self): + raise Exception("boom") + + +class ErrorInAsyncOpenHandler(TestWebSocketHandler): + async def open(self): + await asyncio.sleep(0) + raise Exception("boom") + + +class NoDelayHandler(TestWebSocketHandler): + def open(self): + self.set_nodelay(True) + self.write_message("hello") + + +class WebSocketBaseTestCase(AsyncHTTPTestCase): + def setUp(self): + super().setUp() + self.conns_to_close = [] + + def tearDown(self): + for conn in self.conns_to_close: + conn.close() + super().tearDown() + + @gen.coroutine + def ws_connect(self, path, **kwargs): + ws = yield websocket_connect( + "ws://127.0.0.1:%d%s" % (self.get_http_port(), path), **kwargs + ) + self.conns_to_close.append(ws) + raise gen.Return(ws) + + +class WebSocketTest(WebSocketBaseTestCase): + def get_app(self): + self.close_future = Future() # type: Future[None] + return Application( + [ + ("/echo", EchoHandler, dict(close_future=self.close_future)), + ("/non_ws", NonWebSocketHandler), + ("/redirect", RedirectHandler), + ("/header", HeaderHandler, dict(close_future=self.close_future)), + ( + "/header_echo", + HeaderEchoHandler, + dict(close_future=self.close_future), + ), + ( + "/close_reason", + CloseReasonHandler, + dict(close_future=self.close_future), + ), + ( + "/error_in_on_message", + ErrorInOnMessageHandler, + dict(close_future=self.close_future), + ), + ( + "/async_prepare", + AsyncPrepareHandler, + dict(close_future=self.close_future), + ), + ( + "/path_args/(.*)", + PathArgsHandler, + dict(close_future=self.close_future), + ), + ( + "/coroutine", + CoroutineOnMessageHandler, + dict(close_future=self.close_future), + ), + ("/render", RenderMessageHandler, dict(close_future=self.close_future)), + ( + "/subprotocol", + SubprotocolHandler, + dict(close_future=self.close_future), + ), + ( + "/open_coroutine", + OpenCoroutineHandler, + dict(close_future=self.close_future, test=self), + ), + ("/error_in_open", ErrorInOpenHandler), + ("/error_in_async_open", ErrorInAsyncOpenHandler), + ("/nodelay", NoDelayHandler), + ], + template_loader=DictLoader({"message.html": "{{ message }}"}), + ) + + def get_http_client(self): + # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient. + return SimpleAsyncHTTPClient() + + def tearDown(self): + super().tearDown() + RequestHandler._template_loaders.clear() + + def test_http_request(self): + # WS server, HTTP client. + response = self.fetch("/echo") + self.assertEqual(response.code, 400) + + def test_missing_websocket_key(self): + response = self.fetch( + "/echo", + headers={ + "Connection": "Upgrade", + "Upgrade": "WebSocket", + "Sec-WebSocket-Version": "13", + }, + ) + self.assertEqual(response.code, 400) + + def test_bad_websocket_version(self): + response = self.fetch( + "/echo", + headers={ + "Connection": "Upgrade", + "Upgrade": "WebSocket", + "Sec-WebSocket-Version": "12", + }, + ) + self.assertEqual(response.code, 426) + + @gen_test + def test_websocket_gen(self): + ws = yield self.ws_connect("/echo") + yield ws.write_message("hello") + response = yield ws.read_message() + self.assertEqual(response, "hello") + + def test_websocket_callbacks(self): + with ignore_deprecation(): + websocket_connect( + "ws://127.0.0.1:%d/echo" % self.get_http_port(), callback=self.stop + ) + ws = self.wait().result() + ws.write_message("hello") + ws.read_message(self.stop) + response = self.wait().result() + self.assertEqual(response, "hello") + self.close_future.add_done_callback(lambda f: self.stop()) + ws.close() + self.wait() + + @gen_test + def test_binary_message(self): + ws = yield self.ws_connect("/echo") + ws.write_message(b"hello \xe9", binary=True) + response = yield ws.read_message() + self.assertEqual(response, b"hello \xe9") + + @gen_test + def test_unicode_message(self): + ws = yield self.ws_connect("/echo") + ws.write_message("hello \u00e9") + response = yield ws.read_message() + self.assertEqual(response, "hello \u00e9") + + @gen_test + def test_error_in_closed_client_write_message(self): + ws = yield self.ws_connect("/echo") + ws.close() + with self.assertRaises(WebSocketClosedError): + ws.write_message("hello \u00e9") + + @gen_test + def test_render_message(self): + ws = yield self.ws_connect("/render") + ws.write_message("hello") + response = yield ws.read_message() + self.assertEqual(response, "hello") + + @gen_test + def test_error_in_on_message(self): + ws = yield self.ws_connect("/error_in_on_message") + ws.write_message("hello") + with ExpectLog(app_log, "Uncaught exception"): + response = yield ws.read_message() + self.assertIsNone(response) + + @gen_test + def test_websocket_http_fail(self): + with self.assertRaises(HTTPError) as cm: + yield self.ws_connect("/notfound") + self.assertEqual(cm.exception.code, 404) + + @gen_test + def test_websocket_http_success(self): + with self.assertRaises(WebSocketError): + yield self.ws_connect("/non_ws") + + @gen_test + def test_websocket_http_redirect(self): + with self.assertRaises(HTTPError): + yield self.ws_connect("/redirect") + + @gen_test + def test_websocket_network_fail(self): + sock, port = bind_unused_port() + sock.close() + with self.assertRaises(IOError): + with ExpectLog(gen_log, ".*", required=False): + yield websocket_connect( + "ws://127.0.0.1:%d/" % port, connect_timeout=3600 + ) + + @gen_test + def test_websocket_close_buffered_data(self): + with contextlib.closing( + (yield websocket_connect("ws://127.0.0.1:%d/echo" % self.get_http_port())) + ) as ws: + ws.write_message("hello") + ws.write_message("world") + # Close the underlying stream. + ws.stream.close() + + @gen_test + def test_websocket_headers(self): + # Ensure that arbitrary headers can be passed through websocket_connect. + with contextlib.closing( + ( + yield websocket_connect( + HTTPRequest( + "ws://127.0.0.1:%d/header" % self.get_http_port(), + headers={"X-Test": "hello"}, + ) + ) + ) + ) as ws: + response = yield ws.read_message() + self.assertEqual(response, "hello") + + @gen_test + def test_websocket_header_echo(self): + # Ensure that headers can be returned in the response. + # Specifically, that arbitrary headers passed through websocket_connect + # can be returned. + with contextlib.closing( + ( + yield websocket_connect( + HTTPRequest( + "ws://127.0.0.1:%d/header_echo" % self.get_http_port(), + headers={"X-Test-Hello": "hello"}, + ) + ) + ) + ) as ws: + self.assertEqual(ws.headers.get("X-Test-Hello"), "hello") + self.assertEqual( + ws.headers.get("X-Extra-Response-Header"), "Extra-Response-Value" + ) + + @gen_test + def test_server_close_reason(self): + ws = yield self.ws_connect("/close_reason") + msg = yield ws.read_message() + # A message of None means the other side closed the connection. + self.assertIs(msg, None) + self.assertEqual(ws.close_code, 1001) + self.assertEqual(ws.close_reason, "goodbye") + # The on_close callback is called no matter which side closed. + code, reason = yield self.close_future + # The client echoed the close code it received to the server, + # so the server's close code (returned via close_future) is + # the same. + self.assertEqual(code, 1001) + + @gen_test + def test_client_close_reason(self): + ws = yield self.ws_connect("/echo") + ws.close(1001, "goodbye") + code, reason = yield self.close_future + self.assertEqual(code, 1001) + self.assertEqual(reason, "goodbye") + + @gen_test + def test_write_after_close(self): + ws = yield self.ws_connect("/close_reason") + msg = yield ws.read_message() + self.assertIs(msg, None) + with self.assertRaises(WebSocketClosedError): + ws.write_message("hello") + + @gen_test + def test_async_prepare(self): + # Previously, an async prepare method triggered a bug that would + # result in a timeout on test shutdown (and a memory leak). + ws = yield self.ws_connect("/async_prepare") + ws.write_message("hello") + res = yield ws.read_message() + self.assertEqual(res, "hello") + + @gen_test + def test_path_args(self): + ws = yield self.ws_connect("/path_args/hello") + res = yield ws.read_message() + self.assertEqual(res, "hello") + + @gen_test + def test_coroutine(self): + ws = yield self.ws_connect("/coroutine") + # Send both messages immediately, coroutine must process one at a time. + yield ws.write_message("hello1") + yield ws.write_message("hello2") + res = yield ws.read_message() + self.assertEqual(res, "hello1") + res = yield ws.read_message() + self.assertEqual(res, "hello2") + + @gen_test + def test_check_origin_valid_no_path(self): + port = self.get_http_port() + + url = "ws://127.0.0.1:%d/echo" % port + headers = {"Origin": "http://127.0.0.1:%d" % port} + + with contextlib.closing( + (yield websocket_connect(HTTPRequest(url, headers=headers))) + ) as ws: + ws.write_message("hello") + response = yield ws.read_message() + self.assertEqual(response, "hello") + + @gen_test + def test_check_origin_valid_with_path(self): + port = self.get_http_port() + + url = "ws://127.0.0.1:%d/echo" % port + headers = {"Origin": "http://127.0.0.1:%d/something" % port} + + with contextlib.closing( + (yield websocket_connect(HTTPRequest(url, headers=headers))) + ) as ws: + ws.write_message("hello") + response = yield ws.read_message() + self.assertEqual(response, "hello") + + @gen_test + def test_check_origin_invalid_partial_url(self): + port = self.get_http_port() + + url = "ws://127.0.0.1:%d/echo" % port + headers = {"Origin": "127.0.0.1:%d" % port} + + with self.assertRaises(HTTPError) as cm: + yield websocket_connect(HTTPRequest(url, headers=headers)) + self.assertEqual(cm.exception.code, 403) + + @gen_test + def test_check_origin_invalid(self): + port = self.get_http_port() + + url = "ws://127.0.0.1:%d/echo" % port + # Host is 127.0.0.1, which should not be accessible from some other + # domain + headers = {"Origin": "http://somewhereelse.com"} + + with self.assertRaises(HTTPError) as cm: + yield websocket_connect(HTTPRequest(url, headers=headers)) + + self.assertEqual(cm.exception.code, 403) + + @gen_test + def test_check_origin_invalid_subdomains(self): + port = self.get_http_port() + + # CaresResolver may return ipv6-only results for localhost, but our + # server is only running on ipv4. Test for this edge case and skip + # the test if it happens. + addrinfo = yield Resolver().resolve("localhost", port) + families = {addr[0] for addr in addrinfo} + if socket.AF_INET not in families: + self.skipTest("localhost does not resolve to ipv4") + return + + url = "ws://localhost:%d/echo" % port + # Subdomains should be disallowed by default. If we could pass a + # resolver to websocket_connect we could test sibling domains as well. + headers = {"Origin": "http://subtenant.localhost"} + + with self.assertRaises(HTTPError) as cm: + yield websocket_connect(HTTPRequest(url, headers=headers)) + + self.assertEqual(cm.exception.code, 403) + + @gen_test + def test_subprotocols(self): + ws = yield self.ws_connect( + "/subprotocol", subprotocols=["badproto", "goodproto"] + ) + self.assertEqual(ws.selected_subprotocol, "goodproto") + res = yield ws.read_message() + self.assertEqual(res, "subprotocol=goodproto") + + @gen_test + def test_subprotocols_not_offered(self): + ws = yield self.ws_connect("/subprotocol") + self.assertIs(ws.selected_subprotocol, None) + res = yield ws.read_message() + self.assertEqual(res, "subprotocol=None") + + @gen_test + def test_open_coroutine(self): + self.message_sent = Event() + ws = yield self.ws_connect("/open_coroutine") + yield ws.write_message("hello") + self.message_sent.set() + res = yield ws.read_message() + self.assertEqual(res, "ok") + + @gen_test + def test_error_in_open(self): + with ExpectLog(app_log, "Uncaught exception"): + ws = yield self.ws_connect("/error_in_open") + res = yield ws.read_message() + self.assertIsNone(res) + + @gen_test + def test_error_in_async_open(self): + with ExpectLog(app_log, "Uncaught exception"): + ws = yield self.ws_connect("/error_in_async_open") + res = yield ws.read_message() + self.assertIsNone(res) + + @gen_test + def test_nodelay(self): + ws = yield self.ws_connect("/nodelay") + res = yield ws.read_message() + self.assertEqual(res, "hello") + + +class NativeCoroutineOnMessageHandler(TestWebSocketHandler): + def initialize(self, **kwargs): + super().initialize(**kwargs) + self.sleeping = 0 + + async def on_message(self, message): + if self.sleeping > 0: + self.write_message("another coroutine is already sleeping") + self.sleeping += 1 + await gen.sleep(0.01) + self.sleeping -= 1 + self.write_message(message) + + +class WebSocketNativeCoroutineTest(WebSocketBaseTestCase): + def get_app(self): + return Application([("/native", NativeCoroutineOnMessageHandler)]) + + @gen_test + def test_native_coroutine(self): + ws = yield self.ws_connect("/native") + # Send both messages immediately, coroutine must process one at a time. + yield ws.write_message("hello1") + yield ws.write_message("hello2") + res = yield ws.read_message() + self.assertEqual(res, "hello1") + res = yield ws.read_message() + self.assertEqual(res, "hello2") + + +@abstract_base_test +class CompressionTestMixin(WebSocketBaseTestCase): + MESSAGE = "Hello world. Testing 123 123" + + def get_app(self): + class LimitedHandler(TestWebSocketHandler): + @property + def max_message_size(self): + return 1024 + + def on_message(self, message): + self.write_message(str(len(message))) + + return Application( + [ + ( + "/echo", + EchoHandler, + dict(compression_options=self.get_server_compression_options()), + ), + ( + "/limited", + LimitedHandler, + dict(compression_options=self.get_server_compression_options()), + ), + ] + ) + + def get_server_compression_options(self): + return None + + def get_client_compression_options(self): + return None + + def verify_wire_bytes(self, bytes_in: int, bytes_out: int) -> None: + raise NotImplementedError() + + @gen_test + def test_message_sizes(self): + ws = yield self.ws_connect( + "/echo", compression_options=self.get_client_compression_options() + ) + # Send the same message three times so we can measure the + # effect of the context_takeover options. + for i in range(3): + ws.write_message(self.MESSAGE) + response = yield ws.read_message() + self.assertEqual(response, self.MESSAGE) + self.assertEqual(ws.protocol._message_bytes_out, len(self.MESSAGE) * 3) + self.assertEqual(ws.protocol._message_bytes_in, len(self.MESSAGE) * 3) + self.verify_wire_bytes(ws.protocol._wire_bytes_in, ws.protocol._wire_bytes_out) + + @gen_test + def test_size_limit(self): + ws = yield self.ws_connect( + "/limited", compression_options=self.get_client_compression_options() + ) + # Small messages pass through. + ws.write_message("a" * 128) + response = yield ws.read_message() + self.assertEqual(response, "128") + # This message is too big after decompression, but it compresses + # down to a size that will pass the initial checks. + ws.write_message("a" * 2048) + response = yield ws.read_message() + self.assertIsNone(response) + + +@abstract_base_test +class UncompressedTestMixin(CompressionTestMixin): + """Specialization of CompressionTestMixin when we expect no compression.""" + + def verify_wire_bytes(self, bytes_in, bytes_out): + # Bytes out includes the 4-byte mask key per message. + self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6)) + self.assertEqual(bytes_in, 3 * (len(self.MESSAGE) + 2)) + + +class NoCompressionTest(UncompressedTestMixin): + pass + + +# If only one side tries to compress, the extension is not negotiated. +class ServerOnlyCompressionTest(UncompressedTestMixin): + def get_server_compression_options(self): + return {} + + +class ClientOnlyCompressionTest(UncompressedTestMixin): + def get_client_compression_options(self): + return {} + + +class DefaultCompressionTest(CompressionTestMixin): + def get_server_compression_options(self): + return {} + + def get_client_compression_options(self): + return {} + + def verify_wire_bytes(self, bytes_in, bytes_out): + self.assertLess(bytes_out, 3 * (len(self.MESSAGE) + 6)) + self.assertLess(bytes_in, 3 * (len(self.MESSAGE) + 2)) + # Bytes out includes the 4 bytes mask key per message. + self.assertEqual(bytes_out, bytes_in + 12) + + +@abstract_base_test +class MaskFunctionMixin(unittest.TestCase): + # Subclasses should define self.mask(mask, data) + def mask(self, mask: bytes, data: bytes) -> bytes: + raise NotImplementedError() + + def test_mask(self: typing.Any): + self.assertEqual(self.mask(b"abcd", b""), b"") + self.assertEqual(self.mask(b"abcd", b"b"), b"\x03") + self.assertEqual(self.mask(b"abcd", b"54321"), b"TVPVP") + self.assertEqual(self.mask(b"ZXCV", b"98765432"), b"c`t`olpd") + # Include test cases with \x00 bytes (to ensure that the C + # extension isn't depending on null-terminated strings) and + # bytes with the high bit set (to smoke out signedness issues). + self.assertEqual( + self.mask(b"\x00\x01\x02\x03", b"\xff\xfb\xfd\xfc\xfe\xfa"), + b"\xff\xfa\xff\xff\xfe\xfb", + ) + self.assertEqual( + self.mask(b"\xff\xfb\xfd\xfc", b"\x00\x01\x02\x03\x04\x05"), + b"\xff\xfa\xff\xff\xfb\xfe", + ) + + +class PythonMaskFunctionTest(MaskFunctionMixin): + def mask(self, mask, data): + return _websocket_mask_python(mask, data) + + +@unittest.skipIf(speedups is None, "tornado.speedups module not present") +class CythonMaskFunctionTest(MaskFunctionMixin): + def mask(self, mask, data): + return speedups.websocket_mask(mask, data) + + +class ServerPeriodicPingTest(WebSocketBaseTestCase): + def get_app(self): + class PingHandler(TestWebSocketHandler): + def on_pong(self, data): + self.write_message("got pong") + + return Application( + [("/", PingHandler)], + websocket_ping_interval=0.01, + websocket_ping_timeout=0, + ) + + @gen_test + def test_server_ping(self): + ws = yield self.ws_connect("/") + for i in range(3): + response = yield ws.read_message() + self.assertEqual(response, "got pong") + # TODO: test that the connection gets closed if ping responses stop. + + +class ClientPeriodicPingTest(WebSocketBaseTestCase): + def get_app(self): + class PingHandler(TestWebSocketHandler): + def on_ping(self, data): + self.write_message("got ping") + + return Application([("/", PingHandler)]) + + @gen_test + def test_client_ping(self): + ws = yield self.ws_connect("/", ping_interval=0.01, ping_timeout=0) + for i in range(3): + response = yield ws.read_message() + self.assertEqual(response, "got ping") + ws.close() + + +class ServerPingTimeoutTest(WebSocketBaseTestCase): + def get_app(self): + self.handlers: list[WebSocketHandler] = [] + test = self + + class PingHandler(TestWebSocketHandler): + def initialize(self, close_future=None, compression_options=None): + self.handlers = test.handlers + # capture the handler instance so we can interrogate it later + self.handlers.append(self) + return super().initialize( + close_future=close_future, compression_options=compression_options + ) + + app = Application([("/", PingHandler)]) + return app + + @staticmethod + def install_hook(ws): + """Optionally suppress the client's "pong" response.""" + + ws.drop_pongs = False + ws.pongs_received = 0 + + def wrapper(fcn): + def _inner(opcode: int, data: bytes): + if opcode == 0xA: # NOTE: 0x9=ping, 0xA=pong + ws.pongs_received += 1 + if ws.drop_pongs: + # prevent pong responses + return + # leave all other responses unchanged + return fcn(opcode, data) + + return _inner + + ws.protocol._handle_message = wrapper(ws.protocol._handle_message) + + @gen_test + def test_client_ping_timeout(self): + # websocket client + interval = 0.2 + ws = yield self.ws_connect( + "/", ping_interval=interval, ping_timeout=interval / 4 + ) + self.install_hook(ws) + + # websocket handler (server side) + handler = self.handlers[0] + + for _ in range(5): + # wait for the ping period + yield gen.sleep(interval) + + # connection should still be open from the server end + self.assertIsNone(handler.close_code) + self.assertIsNone(handler.close_reason) + + # connection should still be open from the client end + assert ws.protocol.close_code is None + + # Check that our hook is intercepting messages; allow for + # some variance in timing (due to e.g. cpu load) + self.assertGreaterEqual(ws.pongs_received, 4) + + # suppress the pong response message + ws.drop_pongs = True + + # give the server time to register this + yield gen.sleep(interval * 1.5) + + # connection should be closed from the server side + self.assertEqual(handler.close_code, 1000) + self.assertEqual(handler.close_reason, "ping timed out") + + # client should have received a close operation + self.assertEqual(ws.protocol.close_code, 1000) + + +class PingCalculationTest(unittest.TestCase): + def test_ping_sleep_time(self): + from tornado.websocket import WebSocketProtocol13 + + now = datetime.datetime(2025, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc) + interval = 10 # seconds + last_ping_time = datetime.datetime( + 2025, 1, 1, 11, 59, 54, tzinfo=datetime.timezone.utc + ) + sleep_time = WebSocketProtocol13.ping_sleep_time( + last_ping_time=last_ping_time.timestamp(), + interval=interval, + now=now.timestamp(), + ) + self.assertEqual(sleep_time, 4) + + +class ManualPingTest(WebSocketBaseTestCase): + def get_app(self): + class PingHandler(TestWebSocketHandler): + def on_ping(self, data): + self.write_message(data, binary=isinstance(data, bytes)) + + return Application([("/", PingHandler)]) + + @gen_test + def test_manual_ping(self): + ws = yield self.ws_connect("/") + + self.assertRaises(ValueError, ws.ping, "a" * 126) + + ws.ping("hello") + resp = yield ws.read_message() + # on_ping always sees bytes. + self.assertEqual(resp, b"hello") + + ws.ping(b"binary hello") + resp = yield ws.read_message() + self.assertEqual(resp, b"binary hello") + + +class MaxMessageSizeTest(WebSocketBaseTestCase): + def get_app(self): + return Application([("/", EchoHandler)], websocket_max_message_size=1024) + + @gen_test + def test_large_message(self): + ws = yield self.ws_connect("/") + + # Write a message that is allowed. + msg = "a" * 1024 + ws.write_message(msg) + resp = yield ws.read_message() + self.assertEqual(resp, msg) + + # Write a message that is too large. + ws.write_message(msg + "b") + resp = yield ws.read_message() + # A message of None means the other side closed the connection. + self.assertIs(resp, None) + self.assertEqual(ws.close_code, 1009) + self.assertEqual(ws.close_reason, "message too big") + # TODO: Needs tests of messages split over multiple + # continuation frames. diff --git a/python/user_packages/Python313/site-packages/tornado/test/wsgi_test.py b/python/user_packages/Python313/site-packages/tornado/test/wsgi_test.py new file mode 100644 index 0000000000000000000000000000000000000000..069339fdc50a34a737f7e5f7517c9cb5e76037c7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tornado/test/wsgi_test.py @@ -0,0 +1,116 @@ +import asyncio +import concurrent.futures +import threading + +from wsgiref.validate import validator + +from tornado.routing import RuleRouter +from tornado.testing import AsyncHTTPTestCase, gen_test +from tornado.wsgi import WSGIContainer + + +class WSGIAppMixin: + # TODO: Now that WSGIAdapter is gone, this is a pretty weak test. + def get_executor(self): + raise NotImplementedError() + + def get_app(self): + executor = self.get_executor() + # The barrier test in DummyExecutorTest will always wait the full + # value of this timeout, so we don't want it to be too high. + self.barrier = threading.Barrier(2, timeout=0.3) + + def make_container(app): + return WSGIContainer(validator(app), executor=executor) + + return RuleRouter( + [ + ("/simple", make_container(self.simple_wsgi_app)), + ("/barrier", make_container(self.barrier_wsgi_app)), + ("/streaming_barrier", make_container(self.streaming_barrier_wsgi_app)), + ] + ) + + def respond_plain(self, start_response): + status = "200 OK" + response_headers = [("Content-Type", "text/plain")] + start_response(status, response_headers) + + def simple_wsgi_app(self, environ, start_response): + self.respond_plain(start_response) + return [b"Hello world!"] + + def barrier_wsgi_app(self, environ, start_response): + self.respond_plain(start_response) + try: + n = self.barrier.wait() + except threading.BrokenBarrierError: + return [b"broken barrier"] + else: + return [b"ok %d" % n] + + def streaming_barrier_wsgi_app(self, environ, start_response): + self.respond_plain(start_response) + yield b"ok " + try: + n = self.barrier.wait() + except threading.BrokenBarrierError: + yield b"broken barrier" + else: + yield b"%d" % n + + +class WSGIContainerDummyExecutorTest(WSGIAppMixin, AsyncHTTPTestCase): + def get_executor(self): + return None + + def test_simple(self): + response = self.fetch("/simple") + self.assertEqual(response.body, b"Hello world!") + + @gen_test + async def test_concurrent_barrier(self): + self.barrier.reset() + resps = await asyncio.gather( + self.http_client.fetch(self.get_url("/barrier")), + self.http_client.fetch(self.get_url("/barrier")), + ) + for resp in resps: + self.assertEqual(resp.body, b"broken barrier") + + @gen_test + async def test_concurrent_streaming_barrier(self): + self.barrier.reset() + resps = await asyncio.gather( + self.http_client.fetch(self.get_url("/streaming_barrier")), + self.http_client.fetch(self.get_url("/streaming_barrier")), + ) + for resp in resps: + self.assertEqual(resp.body, b"ok broken barrier") + + +class WSGIContainerThreadPoolTest(WSGIAppMixin, AsyncHTTPTestCase): + def get_executor(self): + return concurrent.futures.ThreadPoolExecutor() + + def test_simple(self): + response = self.fetch("/simple") + self.assertEqual(response.body, b"Hello world!") + + @gen_test + async def test_concurrent_barrier(self): + self.barrier.reset() + resps = await asyncio.gather( + self.http_client.fetch(self.get_url("/barrier")), + self.http_client.fetch(self.get_url("/barrier")), + ) + self.assertEqual([b"ok 0", b"ok 1"], sorted([resp.body for resp in resps])) + + @gen_test + async def test_concurrent_streaming_barrier(self): + self.barrier.reset() + resps = await asyncio.gather( + self.http_client.fetch(self.get_url("/streaming_barrier")), + self.http_client.fetch(self.get_url("/streaming_barrier")), + ) + self.assertEqual([b"ok 0", b"ok 1"], sorted([resp.body for resp in resps])) diff --git a/python/user_packages/Python313/site-packages/tqdm-4.67.3.dist-info/licenses/LICENCE b/python/user_packages/Python313/site-packages/tqdm-4.67.3.dist-info/licenses/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..194caf554f8f10ba4cac8a81b631a61d0d81f60d --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm-4.67.3.dist-info/licenses/LICENCE @@ -0,0 +1,49 @@ +`tqdm` is a product of collaborative work. +Unless otherwise stated, all authors (see commit logs) retain copyright +for their respective work, and release the work under the MIT licence +(text below). + +Exceptions or notable authors are listed below +in reverse chronological order: + +* files: * + MPL-2.0 2015-2026 (c) Casper da Costa-Luis + [casperdcl](https://github.com/casperdcl). +* files: tqdm/_tqdm.py + MIT 2016 (c) [PR #96] on behalf of Google Inc. +* files: tqdm/_tqdm.py README.rst .gitignore + MIT 2013 (c) Noam Yorav-Raphael, original author. + +[PR #96]: https://github.com/tqdm/tqdm/pull/96 + + +Mozilla Public Licence (MPL) v. 2.0 - Exhibit A +----------------------------------------------- + +This Source Code Form is subject to the terms of the +Mozilla Public License, v. 2.0. +If a copy of the MPL was not distributed with this project, +You can obtain one at https://mozilla.org/MPL/2.0/. + + +MIT License (MIT) +----------------- + +Copyright (c) 2013 noamraph + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54063a8427e0601b2379d532268ef0073028b3cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/__main__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0a743f9fefaf55984529e9648015b6a0f2898a7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/__main__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_main.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ba5eed8b7d0e7f4db0b41e4bcf7bc4f1917c6b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_main.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_monitor.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_monitor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6e47b1028f1405ba2a28a3ccb682f6b4fda2e44 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_monitor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a333afee7afcc241eb2bf805d53a2d8fc4a2196 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90000cc02462405335914fe62c2d6025ee3e8f7e Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_gui.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..568e1fa68e5057cdb712d41a214afb32e229578b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_notebook.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45febb23d6a7b597b7f6f440a16879773e086fa1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dc1466f42ba91cf1e59e6cb3f6f3bca78fadb6b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/asyncio.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/asyncio.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d713be466800ce3b58fccbec15a5bd8ce99d29 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/asyncio.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/auto.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/auto.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fd962680ddc4d4e5931d07f2e67d550eae8010a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/auto.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/autonotebook.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/autonotebook.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05c01618985bb8fc00c7fd28678ce083dfa1c2e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/autonotebook.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/cli.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5edd1153923d79909c900e003a84df660491dbd0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/cli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/dask.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/dask.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47efd87f6527c8b88ea181261581b4c00f0f0966 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/dask.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/gui.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/gui.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea896781cb2bdc6144f72e6ead3c0914539768c3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/gui.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/keras.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/keras.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4749708abf713ef408210eed053c5796b55c3891 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/keras.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/notebook.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/notebook.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..658dbc2840f307337682922d683a660123413f75 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/notebook.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/rich.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/rich.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d112505c768588871d6cebd673ac9919dd9b632 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/rich.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/std.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/std.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0495b52f9c5f79757578319dd6f7d429e8d20224 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/std.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/tk.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/tk.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16c16cca691d0f390a90ce76daa2d72a857a2ba6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/tk.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad315b59af72d70d9ef225f4c0388f9a8611272d Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d06d133486d1ec69e0f114957a6b2b86c0e9725e Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/__pycache__/version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__init__.py b/python/user_packages/Python313/site-packages/tqdm/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87ec4601fcff138e0882808237375aed93f5ef35 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/__init__.py @@ -0,0 +1,91 @@ +""" +Thin wrappers around common functions. + +Subpackages contain potentially unstable extensions. +""" +from warnings import warn + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmDeprecationWarning, tqdm +from ..utils import ObjectWrapper + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tenumerate', 'tzip', 'tmap'] + + +class DummyTqdmFile(ObjectWrapper): + """Dummy file-like that will write to tqdm""" + + def __init__(self, wrapped): + super().__init__(wrapped) + self._buf = [] + + def write(self, x, nolock=False): + nl = b"\n" if isinstance(x, bytes) else "\n" + pre, sep, post = x.rpartition(nl) + if sep: + blank = type(nl)() + tqdm.write(blank.join(self._buf + [pre, sep]), + end=blank, file=self._wrapped, nolock=nolock) + self._buf = [post] + else: + self._buf.append(x) + + def __del__(self): + if self._buf: + blank = type(self._buf[0])() + try: + tqdm.write(blank.join(self._buf), end=blank, file=self._wrapped) + except (OSError, ValueError): + pass + + +def builtin_iterable(func): + """Returns `func`""" + warn("This function has no effect, and will be removed in tqdm==5.0.0", + TqdmDeprecationWarning, stacklevel=2) + return func + + +def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, **tqdm_kwargs): + """ + Equivalent of `numpy.ndenumerate` or builtin `enumerate`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + try: + import numpy as np + except ImportError: + pass + else: + if isinstance(iterable, np.ndarray): + return tqdm_class(np.ndenumerate(iterable), total=total or iterable.size, + **tqdm_kwargs) + return enumerate(tqdm_class(iterable, total=total, **tqdm_kwargs), start) + + +def tzip(iter1, *iter2plus, **tqdm_kwargs): + """ + Equivalent of builtin `zip`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + kwargs = tqdm_kwargs.copy() + tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) + yield from zip(tqdm_class(iter1, **kwargs), *iter2plus) + + +def tmap(function, *sequences, **tqdm_kwargs): + """ + Equivalent of builtin `map`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + for i in tzip(*sequences, **tqdm_kwargs): + yield function(*i) diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8843f47ffde32bceefbfa599ea67852fd79a99f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/bells.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/bells.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74382112ea2f8822a438f09f2b6129cb8b2e5033 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/bells.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb8d76099ec05cc851963d322b81db67acafd741 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/concurrent.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/discord.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/discord.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7d236c7161c0f21cfbaf72be0af4fb9085fb46b Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/discord.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/itertools.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/itertools.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c1c504ec19adc7cba48b62280c777d758959a9f Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/itertools.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/logging.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/logging.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3208cd4a30a617d14b4a398ed6ccf21901f2626 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/logging.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/slack.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/slack.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..523e1979644a6d301864c68bcf1cf76b6bca673a Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/slack.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/telegram.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/telegram.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..029bb8059620dd60076079f3f97c65a39795bd74 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/telegram.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-313.pyc b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..641396d495ebd3db4e821ccb181485d3e2dd8988 Binary files /dev/null and b/python/user_packages/Python313/site-packages/tqdm/contrib/__pycache__/utils_worker.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/bells.py b/python/user_packages/Python313/site-packages/tqdm/contrib/bells.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8f4b9ecd894f1edfaa08d9fe730b8d7c8b93e0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/bells.py @@ -0,0 +1,26 @@ +""" +Even more features than `tqdm.auto` (all the bells & whistles): + +- `tqdm.auto` +- `tqdm.tqdm.pandas` +- `tqdm.contrib.telegram` + + uses `${TQDM_TELEGRAM_TOKEN}` and `${TQDM_TELEGRAM_CHAT_ID}` +- `tqdm.contrib.discord` + + uses `${TQDM_DISCORD_TOKEN}` and `${TQDM_DISCORD_CHANNEL_ID}` +""" +__all__ = ['tqdm', 'trange'] +import warnings +from os import getenv + +if getenv("TQDM_SLACK_TOKEN") and getenv("TQDM_SLACK_CHANNEL"): + from .slack import tqdm, trange +elif getenv("TQDM_TELEGRAM_TOKEN") and getenv("TQDM_TELEGRAM_CHAT_ID"): + from .telegram import tqdm, trange +elif getenv("TQDM_DISCORD_TOKEN") and getenv("TQDM_DISCORD_CHANNEL_ID"): + from .discord import tqdm, trange +else: + from ..auto import tqdm, trange + +with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=FutureWarning) + tqdm.pandas() diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/concurrent.py b/python/user_packages/Python313/site-packages/tqdm/contrib/concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..cd81d622a1309df179042159a56cef4f8c309224 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/concurrent.py @@ -0,0 +1,105 @@ +""" +Thin wrappers around `concurrent.futures`. +""" +from contextlib import contextmanager +from operator import length_hint +from os import cpu_count + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['thread_map', 'process_map'] + + +@contextmanager +def ensure_lock(tqdm_class, lock_name=""): + """get (create if necessary) and then restore `tqdm_class`'s lock""" + old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock + lock = old_lock or tqdm_class.get_lock() # maybe create a new lock + lock = getattr(lock, lock_name, lock) # maybe subtype + tqdm_class.set_lock(lock) + yield lock + if old_lock is None: + del tqdm_class._lock + else: + tqdm_class.set_lock(old_lock) + + +def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs): + """ + Implementation of `thread_map` and `process_map`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + max_workers : [default: min(32, cpu_count() + 4)]. + chunksize : [default: 1]. + lock_name : [default: "":str]. + """ + kwargs = tqdm_kwargs.copy() + if "total" not in kwargs: + kwargs["total"] = length_hint(iterables[0]) + tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) + max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4)) + chunksize = kwargs.pop("chunksize", 1) + lock_name = kwargs.pop("lock_name", "") + with ensure_lock(tqdm_class, lock_name=lock_name) as lk: + # share lock in case workers are already using `tqdm` + with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock, + initargs=(lk,)) as ex: + return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs)) + + +def thread_map(fn, *iterables, **tqdm_kwargs): + """ + Equivalent of `list(map(fn, *iterables))` + driven by `concurrent.futures.ThreadPoolExecutor`. + + Parameters + ---------- + tqdm_class : optional + `tqdm` class to use for bars [default: tqdm.auto.tqdm]. + max_workers : int, optional + Maximum number of workers to spawn; passed to + `concurrent.futures.ThreadPoolExecutor.__init__`. + [default: max(32, cpu_count() + 4)]. + """ + from concurrent.futures import ThreadPoolExecutor + return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs) + + +def process_map(fn, *iterables, **tqdm_kwargs): + """ + Equivalent of `list(map(fn, *iterables))` + driven by `concurrent.futures.ProcessPoolExecutor`. + + Parameters + ---------- + tqdm_class : optional + `tqdm` class to use for bars [default: tqdm.auto.tqdm]. + max_workers : int, optional + Maximum number of workers to spawn; passed to + `concurrent.futures.ProcessPoolExecutor.__init__`. + [default: min(32, cpu_count() + 4)]. + chunksize : int, optional + Size of chunks sent to worker processes; passed to + `concurrent.futures.ProcessPoolExecutor.map`. [default: 1]. + lock_name : str, optional + Member of `tqdm_class.get_lock()` to use [default: mp_lock]. + """ + from concurrent.futures import ProcessPoolExecutor + if iterables and "chunksize" not in tqdm_kwargs: + # default `chunksize=1` has poor performance for large iterables + # (most time spent dispatching items to workers). + longest_iterable_len = max(map(length_hint, iterables)) + if longest_iterable_len > 1000: + from warnings import warn + warn("Iterable length %d > 1000 but `chunksize` is not set." + " This may seriously degrade multiprocess performance." + " Set `chunksize=1` or more." % longest_iterable_len, + TqdmWarning, stacklevel=2) + if "lock_name" not in tqdm_kwargs: + tqdm_kwargs = tqdm_kwargs.copy() + tqdm_kwargs["lock_name"] = "mp_lock" + return _executor_map(ProcessPoolExecutor, fn, *iterables, **tqdm_kwargs) diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/discord.py b/python/user_packages/Python313/site-packages/tqdm/contrib/discord.py new file mode 100644 index 0000000000000000000000000000000000000000..574baa84bbbeb5afce4a49f23edac894d680ca82 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/discord.py @@ -0,0 +1,156 @@ +""" +Sends updates to a Discord bot. + +Usage: +>>> from tqdm.contrib.discord import tqdm, trange +>>> for i in trange(10, token='{token}', channel_id='{channel_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-discord.png) +""" +from os import getenv +from warnings import warn + +from requests import Session +from requests.utils import default_user_agent + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning +from ..version import __version__ +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["casperdcl", "guigoruiz1"]} +__all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange'] + + +class DiscordIO(MonoWorker): + """Non-blocking file-like IO using a Discord Bot.""" + API = "https://discord.com/api/v10" + UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}" + + def __init__(self, token, channel_id): + """Creates a new message in the given `channel_id`.""" + super().__init__() + self.token = token + self.channel_id = channel_id + self.session = Session() + self.text = self.__class__.__name__ + self.message_id + + @property + def message_id(self): + if hasattr(self, '_message_id'): + return self._message_id + try: + res = self.session.post( + f'{self.API}/channels/{self.channel_id}/messages', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, + json={'content': f"`{self.text}`"}).json() + except Exception as e: + tqdm_auto.write(str(e)) + else: + if res.get('error_code') == 429: + warn("Creation rate limit: try increasing `mininterval`.", + TqdmWarning, stacklevel=2) + else: + self._message_id = res['id'] + return self._message_id + + def write(self, s): + """Replaces internal `message_id`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # avoid duplicate message Bot error + message_id = self.message_id + if message_id is None: + return + self.text = s + try: + future = self.submit( + self.session.patch, + f'{self.API}/channels/{self.channel_id}/messages/{message_id}', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}, + json={'content': f"`{self.text}`"}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + def delete(self): + """Deletes internal `message_id`.""" + try: + future = self.submit( + self.session.delete, + f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}', + headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_discord(tqdm_auto): + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot. + May take a few seconds to create (`__init__`). + + - create a discord bot (not public, no requirement of OAuth2 code + grant, only send message permissions) & invite it to a channel: + + - copy the bot `{token}` & `{channel_id}` and paste below + + >>> from tqdm.contrib.discord import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'): + ... ... + """ + def __init__(self, *args, **kwargs): + """ + Parameters + ---------- + token : str, required. Discord bot token + [default: ${TQDM_DISCORD_TOKEN}]. + channel_id : int, required. Discord channel ID + [default: ${TQDM_DISCORD_CHANNEL_ID}]. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + self.dio = DiscordIO( + kwargs.pop('token', getenv('TQDM_DISCORD_TOKEN')), + kwargs.pop('channel_id', getenv('TQDM_DISCORD_CHANNEL_ID'))) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '{bar:10u}').replace('{bar}', '{bar:10u}') + else: + fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}' + self.dio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.dio.write("") + + def close(self): + if self.disable: + return + super().close() + if not (self.leave or (self.leave is None and self.pos == 0)): + self.dio.delete() + + +def tdrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.discord.tqdm(range(*args), **kwargs)`.""" + return tqdm_discord(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_discord +trange = tdrange diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/itertools.py b/python/user_packages/Python313/site-packages/tqdm/contrib/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..e67651a41a6b8760d9b928ea48239e4611d70315 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/itertools.py @@ -0,0 +1,35 @@ +""" +Thin wrappers around `itertools`. +""" +import itertools + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['product'] + + +def product(*iterables, **tqdm_kwargs): + """ + Equivalent of `itertools.product`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + """ + kwargs = tqdm_kwargs.copy() + tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) + try: + lens = list(map(len, iterables)) + except TypeError: + total = None + else: + total = 1 + for i in lens: + total *= i + kwargs.setdefault("total", total) + with tqdm_class(**kwargs) as t: + it = itertools.product(*iterables) + for i in it: + yield i + t.update() diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/logging.py b/python/user_packages/Python313/site-packages/tqdm/contrib/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..e06febe37b5d70b5296804c55dca48a397c250e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/logging.py @@ -0,0 +1,126 @@ +""" +Helper functionality for interoperability with stdlib `logging`. +""" +import logging +import sys +from contextlib import contextmanager + +try: + from typing import Iterator, List, Optional, Type # noqa: F401 +except ImportError: + pass + +from ..std import tqdm as std_tqdm + + +class _TqdmLoggingHandler(logging.StreamHandler): + def __init__( + self, + tqdm_class=std_tqdm # type: Type[std_tqdm] + ): + super().__init__() + self.tqdm_class = tqdm_class + + def emit(self, record): + try: + msg = self.format(record) + self.tqdm_class.write(msg, file=self.stream) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise + except: # noqa pylint: disable=bare-except + self.handleError(record) + + +def _is_console_logging_handler(handler): + return (isinstance(handler, logging.StreamHandler) + and handler.stream in {sys.stdout, sys.stderr}) + + +def _get_first_found_console_logging_handler(handlers): + for handler in handlers: + if _is_console_logging_handler(handler): + return handler + + +@contextmanager +def logging_redirect_tqdm( + loggers=None, # type: Optional[List[logging.Logger]], + tqdm_class=std_tqdm # type: Type[std_tqdm] +): + # type: (...) -> Iterator[None] + """ + Context manager redirecting console logging to `tqdm.write()`, leaving + other logging handlers (e.g. log files) unaffected. + + Parameters + ---------- + loggers : list, optional + Which handlers to redirect (default: [logging.root]). + tqdm_class : optional + + Example + ------- + ```python + import logging + from tqdm import trange + from tqdm.contrib.logging import logging_redirect_tqdm + + LOG = logging.getLogger(__name__) + + if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + with logging_redirect_tqdm(): + for i in trange(9): + if i == 4: + LOG.info("console logging redirected to `tqdm.write()`") + # logging restored + ``` + """ + if loggers is None: + loggers = [logging.root] + original_handlers_list = [logger.handlers for logger in loggers] + try: + for logger in loggers: + tqdm_handler = _TqdmLoggingHandler(tqdm_class) + orig_handler = _get_first_found_console_logging_handler(logger.handlers) + if orig_handler is not None: + tqdm_handler.setFormatter(orig_handler.formatter) + tqdm_handler.stream = orig_handler.stream + logger.handlers = [ + handler for handler in logger.handlers + if not _is_console_logging_handler(handler)] + [tqdm_handler] + yield + finally: + for logger, original_handlers in zip(loggers, original_handlers_list): + logger.handlers = original_handlers + + +@contextmanager +def tqdm_logging_redirect( + *args, + # loggers=None, # type: Optional[List[logging.Logger]] + # tqdm=None, # type: Optional[Type[tqdm.tqdm]] + **kwargs +): + # type: (...) -> Iterator[None] + """ + Convenience shortcut for: + ```python + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar + ``` + + Parameters + ---------- + tqdm_class : optional, (default: tqdm.std.tqdm). + loggers : optional, list. + **tqdm_kwargs : passed to `tqdm_class`. + """ + tqdm_kwargs = kwargs.copy() + loggers = tqdm_kwargs.pop('loggers', None) + tqdm_class = tqdm_kwargs.pop('tqdm_class', std_tqdm) + with tqdm_class(*args, **tqdm_kwargs) as pbar: + with logging_redirect_tqdm(loggers=loggers, tqdm_class=tqdm_class): + yield pbar diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/slack.py b/python/user_packages/Python313/site-packages/tqdm/contrib/slack.py new file mode 100644 index 0000000000000000000000000000000000000000..9bca8ee98904ce869a4f8d6417bbdc4f00b38751 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/slack.py @@ -0,0 +1,120 @@ +""" +Sends updates to a Slack app. + +Usage: +>>> from tqdm.contrib.slack import tqdm, trange +>>> for i in trange(10, token='{token}', channel='{channel}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-slack.png) +""" +import logging +from os import getenv + +try: + from slack_sdk import WebClient +except ImportError: + raise ImportError("Please `pip install slack-sdk`") + +from ..auto import tqdm as tqdm_auto +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]} +__all__ = ['SlackIO', 'tqdm_slack', 'tsrange', 'tqdm', 'trange'] + + +class SlackIO(MonoWorker): + """Non-blocking file-like IO using a Slack app.""" + def __init__(self, token, channel): + """Creates a new message in the given `channel`.""" + super().__init__() + self.client = WebClient(token=token) + self.text = self.__class__.__name__ + try: + self.message = self.client.chat_postMessage(channel=channel, text=self.text) + except Exception as e: + tqdm_auto.write(str(e)) + self.message = None + + def write(self, s): + """Replaces internal `message`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # skip duplicate message + message = self.message + if message is None: + return + self.text = s + try: + future = self.submit(self.client.chat_update, channel=message['channel'], + ts=message['ts'], text='`' + s + '`') + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_slack(tqdm_auto): + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Slack app. + May take a few seconds to create (`__init__`). + + - create a Slack app with the `chat:write` scope & invite it to a + channel: + - copy the bot `{token}` & `{channel}` and paste below + >>> from tqdm.contrib.slack import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', channel='{channel}'): + ... ... + """ + def __init__(self, *args, **kwargs): + """ + Parameters + ---------- + token : str, required. Slack token + [default: ${TQDM_SLACK_TOKEN}]. + channel : int, required. Slack channel + [default: ${TQDM_SLACK_CHANNEL}]. + mininterval : float, optional. + Minimum of [default: 1.5] to avoid rate limit. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + logging.getLogger("HTTPClient").setLevel(logging.WARNING) + self.sio = SlackIO( + kwargs.pop('token', getenv("TQDM_SLACK_TOKEN")), + kwargs.pop('channel', getenv("TQDM_SLACK_CHANNEL"))) + kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5)) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '`{bar:10}`').replace('{bar}', '`{bar:10u}`') + else: + fmt['bar_format'] = '{l_bar}`{bar:10}`{r_bar}' + if fmt['ascii'] is False: + fmt['ascii'] = [":black_square:", ":small_blue_diamond:", ":large_blue_diamond:", + ":large_blue_square:"] + fmt['ncols'] = 336 + self.sio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.sio.write("") + + +def tsrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.slack.tqdm(range(*args), **kwargs)`.""" + return tqdm_slack(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_slack +trange = tsrange diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/telegram.py b/python/user_packages/Python313/site-packages/tqdm/contrib/telegram.py new file mode 100644 index 0000000000000000000000000000000000000000..019151800bc0c4c4fc543314b6398aa602b0692a --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/telegram.py @@ -0,0 +1,153 @@ +""" +Sends updates to a Telegram bot. + +Usage: +>>> from tqdm.contrib.telegram import tqdm, trange +>>> for i in trange(10, token='{token}', chat_id='{chat_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif) +""" +from os import getenv +from warnings import warn + +from requests import Session + +from ..auto import tqdm as tqdm_auto +from ..std import TqdmWarning +from .utils_worker import MonoWorker + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange'] + + +class TelegramIO(MonoWorker): + """Non-blocking file-like IO using a Telegram Bot.""" + API = 'https://api.telegram.org/bot' + + def __init__(self, token, chat_id): + """Creates a new message in the given `chat_id`.""" + super().__init__() + self.token = token + self.chat_id = chat_id + self.session = Session() + self.text = self.__class__.__name__ + self.message_id + + @property + def message_id(self): + if hasattr(self, '_message_id'): + return self._message_id + try: + res = self.session.post( + self.API + '%s/sendMessage' % self.token, + data={'text': '`' + self.text + '`', 'chat_id': self.chat_id, + 'parse_mode': 'MarkdownV2'}).json() + except Exception as e: + tqdm_auto.write(str(e)) + else: + if res.get('error_code') == 429: + warn("Creation rate limit: try increasing `mininterval`.", + TqdmWarning, stacklevel=2) + else: + self._message_id = res['result']['message_id'] + return self._message_id + + def write(self, s): + """Replaces internal `message_id`'s text with `s`.""" + if not s: + s = "..." + s = s.replace('\r', '').strip() + if s == self.text: + return # avoid duplicate message Bot error + message_id = self.message_id + if message_id is None: + return + self.text = s + try: + future = self.submit( + self.session.post, self.API + '%s/editMessageText' % self.token, + data={'text': '`' + s + '`', 'chat_id': self.chat_id, + 'message_id': message_id, 'parse_mode': 'MarkdownV2'}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + def delete(self): + """Deletes internal `message_id`.""" + try: + future = self.submit( + self.session.post, self.API + '%s/deleteMessage' % self.token, + data={'chat_id': self.chat_id, 'message_id': self.message_id}) + except Exception as e: + tqdm_auto.write(str(e)) + else: + return future + + +class tqdm_telegram(tqdm_auto): + """ + Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot. + May take a few seconds to create (`__init__`). + + - create a bot + - copy its `{token}` + - add the bot to a chat and send it a message such as `/start` + - go to to find out + the `{chat_id}` + - paste the `{token}` & `{chat_id}` below + + >>> from tqdm.contrib.telegram import tqdm, trange + >>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'): + ... ... + """ + def __init__(self, *args, **kwargs): + """ + Parameters + ---------- + token : str, required. Telegram token + [default: ${TQDM_TELEGRAM_TOKEN}]. + chat_id : str, required. Telegram chat ID + [default: ${TQDM_TELEGRAM_CHAT_ID}]. + + See `tqdm.auto.tqdm.__init__` for other parameters. + """ + if not kwargs.get('disable'): + kwargs = kwargs.copy() + self.tgio = TelegramIO( + kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')), + kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID'))) + super().__init__(*args, **kwargs) + + def display(self, **kwargs): + super().display(**kwargs) + fmt = self.format_dict + if fmt.get('bar_format', None): + fmt['bar_format'] = fmt['bar_format'].replace( + '', '{bar:10u}').replace('{bar}', '{bar:10u}') + else: + fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}' + self.tgio.write(self.format_meter(**fmt)) + + def clear(self, *args, **kwargs): + super().clear(*args, **kwargs) + if not self.disable: + self.tgio.write("") + + def close(self): + if self.disable: + return + super().close() + if not (self.leave or (self.leave is None and self.pos == 0)): + self.tgio.delete() + + +def ttgrange(*args, **kwargs): + """Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`.""" + return tqdm_telegram(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_telegram +trange = ttgrange diff --git a/python/user_packages/Python313/site-packages/tqdm/contrib/utils_worker.py b/python/user_packages/Python313/site-packages/tqdm/contrib/utils_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..89fafc8c92f8ed085077b37eb58329f2588bd5d7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/tqdm/contrib/utils_worker.py @@ -0,0 +1,38 @@ +""" +IO/concurrency helpers for `tqdm.contrib`. +""" +from collections import deque +from concurrent.futures import ThreadPoolExecutor + +from ..auto import tqdm as tqdm_auto + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['MonoWorker'] + + +class MonoWorker: + """ + Supports one running task and one waiting task. + The waiting task is the most recent submitted (others are discarded). + """ + def __init__(self): + self.pool = ThreadPoolExecutor(max_workers=1) + self.futures = deque([], 2) + + def submit(self, func, *args, **kwargs): + """`func(*args, **kwargs)` may replace currently waiting task.""" + futures = self.futures + if len(futures) == futures.maxlen: + running = futures.popleft() + if not running.done(): + if len(futures): # clear waiting + waiting = futures.pop() + waiting.cancel() + futures.appendleft(running) # re-insert running + try: + waiting = self.pool.submit(func, *args, **kwargs) + except Exception as e: + tqdm_auto.write(str(e)) + else: + futures.append(waiting) + return waiting diff --git a/python/user_packages/Python313/site-packages/typer-0.25.1.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/typer-0.25.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/typer-0.25.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/typer/.agents/skills/typer/SKILL.md b/python/user_packages/Python313/site-packages/typer/.agents/skills/typer/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..19b63c491f8b77605231fccb3b1f7a3ce7a7d882 --- /dev/null +++ b/python/user_packages/Python313/site-packages/typer/.agents/skills/typer/SKILL.md @@ -0,0 +1,266 @@ +--- +name: typer +description: Typer best practices and conventions. Use when working with Typer CLIs. Keeps Typer code clean and up to date with the latest features and patterns, updated with new versions. Write new code or refactor and update old code. +--- + +# Typer + +Official Typer skill to write code with best practices, keeping up to date with new versions and features. + +## Installing typer + +In a virtual environment, `pip install typer` (with pip) or `uv pip install typer` (with uv). For your library/project, add `typer` to the dependencies in `pyproject.toml`. + +Do not install `typer-slim` or `typer-cli`, they are both deprecated and will now simply install `typer`. + +Typer supports Python 3.10 and above. + +## Use an explicit `Typer` app + +For maximum generalizability, create an explicit Typer app and register subcommand(s), instead of using `typer.run`: + +```python +import typer + +app = typer.Typer() + + +@app.command() +def hello(): + print(f"Hello World") + + +if __name__ == "__main__": + app() +``` + +instead of: + +```python +# DO NOT DO THIS: Not extensible. Use Typer() instead. +import typer + + +def main(): + print(f"Hello World") + + +if __name__ == "__main__": + typer.run(main) +``` + +## Execute the app + +To execute the app in the terminal, run + +```bash +python main.py +``` + +When multiple commands are registered to the Typer app, you have to add the command name: + +```bash +python main.py hello +``` + +To see the automatically generated help documentation, run + +```bash +python main.py --help +``` + +or set `no_args_is_help` to `True` when creating the `Typer()` add to automatically show the help when running a command without any arguments. + +## Use `Annotated` + +Always prefer the `Annotated` style for declarations of CLI arguments and options. + +It allows us to pass additional metadata that can be used by Typer. + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def hello(name: Annotated[str, typer.Argument()] = "World"): + # Note that name is an optional Argument, as a default is provided + print(f"Hello {name}") + + +if __name__ == "__main__": + app() +``` + +This program can be run as-is, or can provide a specific name: + +```bash +python main.py +python main.py Rick +``` + +An older way of setting a default value is this: +```python +# DO NOT DO THIS: old style. Use Annotated instead. + +@app.command() +def main(name: str = typer.Argument(default="World")): + # Note that name is an optional Argument, as a default is provided + print(f"Hello {name}") +``` + +Similarly, the old style could use ellipsis (...) to explicitely mark an argument as required. + +```python +# DO NOT DO THIS: old style. Use Annotated without a default value instead. + +@app.command() +def main(name: str = typer.Argument(default=...)): + # Note that name is now a required Argument + print(f"Hello {name}") +``` + +## CLI Options + +CLI options are declared in a similar fashion as arguments, but will be called on the CLI with a single dash (single letter) or 2 dashes (full name): + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def main(user_name: Annotated[str, typer.Option("--name", "-n")]): + # On the CLI, the required user name can be specified with -n or --name + print(f"Hello {user_name}") + + +if __name__ == "__main__": + app() +``` + +You can run this program as such: + +```bash +python main.py -n "Rick" +python main.py --name "Morty" +``` + +### CLI options with multiple values + +By declaring a CLI option as a list, it can receive multiple values: + +```python +from typing import Annotated + +import typer + +app = typer.Typer() + + +@app.command() +def main(user: Annotated[list[str] | None, typer.Option()] = None): + if not user: + print(f"No users provided!") + raise typer.Abort() + for u in user: + print(f"Processing user: {u}") + + +if __name__ == "__main__": + app() +``` + +This can be executed like so: + +```bash +python main.py --user Rick --user Morty --user Summer +``` + +## Rich + +By default, Rich can be used with its custom markup syntax to set colors and styles, e.g. + +```python +from rich import print + +print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:") +``` + +Typer supports using Rich formatting in the docstrings and the help messages of CLI arguments and CLI options. + + +```python +from typing import Annotated + +import typer + +app = typer.Typer(rich_markup_mode="rich") + + +@app.command() +def create( + username: Annotated[ + str, typer.Argument(help="The username to be [green]created[/green]") + ], +): + """ + [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles: + + This requires a [underline]username[/underline]. + """ + print(f"Creating user: {username}") + + +@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].") +def delete( + username: Annotated[ + str, typer.Argument(help="The username to be [red]deleted[/red]") + ], +): + """ + Some internal utility function to delete. + """ + print(f"Deleting user: {username}") + + +if __name__ == "__main__": + app() +``` + +To disable Rich formatting, set `rich_markup_mode` to `None` when creating a `Typer()` app. By default (when no value is given), Rich formatting is enabled. + +### Rich markdown + +You can also set `rich_markup_mode` to `"markdown"` to use Markdown in the docstring: + +```python +from typing import Annotated + +import typer + +app = typer.Typer(rich_markup_mode="markdown") + +@app.command(help="**Delete** a user with *USERNAME*.") +def delete( + username: Annotated[str, typer.Argument(help="The username to be **deleted** :boom:")] +): + print(f"Deleting user: {username}") + +if __name__ == "__main__": + app() +``` + +## Click + +Originally, Typer was built on Click. However, going forward Typer will vendor Click. As such, Click extensions should not be used anymore. + +Other settings of `Option` and `Argument` that came from Click but shouldn't be used in Typer anymore, include: `expose_value`, `shell_complete`, `show_choices`, `errors`, `prompt_required`, `is_flag`, `flag_value` and `allow_from_autoenv`. + +Code bases using these should be refactored to use pure Typer functionality. diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab327bde66e90dcde65fdd894859daa0885ad415 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/__main__.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18737f6c8cc48e7cd83d631207369a578a14f49b Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/__main__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_classes.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_classes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01d141c677d47c945a0f26ee3586454b897c51ab Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_classes.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_shared.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_shared.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df3f7ed029470f982f44216e1d5e864f4c55e38d Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/_completion_shared.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/_types.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1582ffd4ef426be049b465f784c9d4a916364859 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/_types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/_typing.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/_typing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..289a0bf36df86dc11d6ae2a7c166d39c20ef41c8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/_typing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/cli.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52fbcba97c8b9a6080690ca91abe016d456466d5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/cli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/colors.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/colors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60e67a1d4ebed4aea8ab3359a5f3bcfdc4e50583 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/colors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/completion.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/completion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73a4879321e73e4d5cd568b2cb7712e76ed059cf Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/completion.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/core.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0185feeef10c8ec8aea5eefaeceab3d4cb643e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/core.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/main.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4714764b68a2f661e8a41b1801a59a27332ec8aa Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/main.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/models.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2afe2391032f8bde47a72afe2eb6360e80205863 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/models.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/params.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/params.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25e93009d88b662b890a0dee268116ee90dd8bbc Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/params.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/rich_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/rich_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4665849fc84563ff61aa7b3d6be0fd0a954256e Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/rich_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/testing.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/testing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a204d513f2535027893d8fdb1193edc074201daf Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/testing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typer/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/typer/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f604f60683b6403b92c804626ceeaf5d509f9cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/typer/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/python/user_packages/Python313/site-packages/typing_extensions-4.15.0.dist-info/licenses/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e825ad51621c5e34d370ba64f13f6854d89456a6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pydantic Services Inc. 2025 to present + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccdf377fae4d765cc6d3310a1e7d1f9b93407413 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..818d59d8f382ef54c7957bfa813cc1812145437f Binary files /dev/null and b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a620952770cf1e74a5fbdba6d7633217e052dd6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt b/python/user_packages/Python313/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3-2.7.0.dist-info/licenses/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2008-2020 Andrey Petrov and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec43392241ff03aac2d711d5e4b80a120b254ae Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/_base_connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_base_connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3985b6ff68a335ab4c20c34cc710e06034978d5d Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_base_connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/_collections.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_collections.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9133b201e7e85496b64812292d1fc82bfd57277c Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_collections.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/_request_methods.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_request_methods.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f080855372f4da1c43bbdbaee15ad29b5a35c8d6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_request_methods.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2037b8d9c671e6fdc5f13edc48959396ef607961 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21cd57b96c41b6699c9bbc911acdd6d1cb49a9e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/connectionpool.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/connectionpool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03d5e0ffb886424a8608fb6c18a35136512c63cb Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/connectionpool.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6231001e80e6856095dbecc1b2dde2b5f0304f96 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/exceptions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/fields.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/fields.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1872496524023112badf96fa92833d9406351aa2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/fields.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/filepost.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/filepost.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d4f7a8865c25fb4ed4e3ec872fb15404ea5b1b7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/filepost.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/poolmanager.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/poolmanager.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ac7d98908fdf7571df7efee011b3c862a249fb6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/poolmanager.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/__pycache__/response.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/__pycache__/response.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4823679068e016a9fe6a1dcbc89a1ac5aa442573 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/__pycache__/response.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/__init__.py b/python/user_packages/Python313/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cc7698662d2b34f0aabcb491c00aa40e5132ddc Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fee8cad82f36c595f17d106267a3e669383d3dc Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/socks.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/socks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a167034757fea9597d4cc643d11bd219b38e9040 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/__pycache__/socks.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__init__.py b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b62b25e932566f7ae7599c1cedec2b8f30d95b --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] + urllib3.connection.VerifiedHTTPSConnection = EmscriptenHTTPSConnection # type: ignore[assignment] diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498717ce92c27a64f4cc76317034df4b83210491 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eb55bc981a2190935a9a87d3bf010563a62f836 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f61a616e8f881fd068691b443d58151deab8f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f000e7036f61c90adfafead657d594b981dd367f Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d33a92138a758c0392a44ed88a521452dc3f2c5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/connection.py b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..63f79dd3be803db09671c909f79316c3f65d6916 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + response_class: type[BaseHTTPResponse] = EmscriptenHttpResponseWrapper + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + if self.port is not None: + port = f":{self.port}" + else: + port = "" + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}{port}{url}" + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: ( + None | _TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..faf141e1fa4113a0c14480d1681ddecb9678ced4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = new Map(); +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + connections.delete(connectionID); + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections.get(connectionID); + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + connections.delete(connectionID); + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections.get(connectionID).value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections.get(connectionID).curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections.set(connectionID, { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }); + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/fetch.py b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..612cfddc4c28d2f0edf47522278fa6d9b7906623 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/fetch.py @@ -0,0 +1,726 @@ +""" +Support for streaming http requests in emscripten. + +A few caveats - + +If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled +https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md +*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the +JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case +timeouts and streaming should just work. + +Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. + +This approach has several caveats: + +Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. +Streaming only works if you're running pyodide in a web worker. + +Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch +operation, so it requires that you have crossOriginIsolation enabled, by serving over https +(or from localhost) with the two headers below set: + + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + +You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in +JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole +request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. + +Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once +control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. + +NB: in this code, there are a lot of JavaScript objects. They are named js_* +to make it clear what type of object they are. +""" + +from __future__ import annotations + +import io +import json +from email.parser import Parser +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +import js # type: ignore[import-not-found] +from pyodide.ffi import ( # type: ignore[import-not-found] + JsArray, + JsException, + JsProxy, + to_js, +) + +if TYPE_CHECKING: + from typing_extensions import Buffer + +from .request import EmscriptenRequest +from .response import EmscriptenResponse + +""" +There are some headers that trigger unintended CORS preflight requests. +See also https://github.com/koenvo/pyodide-http/issues/22 +""" +HEADERS_TO_IGNORE = ("user-agent",) + +SUCCESS_HEADER = -1 +SUCCESS_EOF = -2 +ERROR_TIMEOUT = -3 +ERROR_EXCEPTION = -4 + + +class _RequestError(Exception): + def __init__( + self, + message: str | None = None, + *, + request: EmscriptenRequest | None = None, + response: EmscriptenResponse | None = None, + ): + self.request = request + self.response = response + self.message = message + super().__init__(self.message) + + +class _StreamingError(_RequestError): + pass + + +class _TimeoutError(_RequestError): + pass + + +def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: + return to_js(dict_val, dict_converter=js.Object.fromEntries) + + +class _ReadStream(io.RawIOBase): + def __init__( + self, + int_buffer: JsArray, + byte_buffer: JsArray, + timeout: float, + worker: JsProxy, + connection_id: int, + request: EmscriptenRequest, + ): + self.int_buffer = int_buffer + self.byte_buffer = byte_buffer + self.read_pos = 0 + self.read_len = 0 + self.connection_id = connection_id + self.worker = worker + self.timeout = int(1000 * timeout) if timeout > 0 else None + self.is_live = True + self._is_closed = False + self.request: EmscriptenRequest | None = request + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.int_buffer = None + self.byte_buffer = None + self._is_closed = True + self.request = None + if self.is_live: + self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) + self.is_live = False + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def readinto(self, byte_obj: Buffer) -> int: + if not self.int_buffer: + raise _StreamingError( + "No buffer for stream in _ReadStream.readinto", + request=self.request, + response=None, + ) + if self.read_len == 0: + # wait for the worker to send something + js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) + self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) + if ( + js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) + == "timed-out" + ): + raise _TimeoutError + data_len = self.int_buffer[0] + if data_len > 0: + self.read_len = data_len + self.read_pos = 0 + elif data_len == ERROR_EXCEPTION: + string_len = self.int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", + request=self.request, + response=None, + ) + else: + # EOF, free the buffers and return zero + # and free the request + self.is_live = False + self.close() + return 0 + # copy from int32array to python bytes + ret_length = min(self.read_len, len(memoryview(byte_obj))) + subarray = self.byte_buffer.subarray( + self.read_pos, self.read_pos + ret_length + ).to_py() + memoryview(byte_obj)[0:ret_length] = subarray + self.read_len -= ret_length + self.read_pos += ret_length + return ret_length + + +class _StreamingFetcher: + def __init__(self) -> None: + # make web-worker and data buffer on startup + self.streaming_ready = False + streaming_worker_code = ( + files(__package__) + .joinpath("emscripten_fetch_worker.js") + .read_text(encoding="utf-8") + ) + js_data_blob = js.Blob.new( + to_js([streaming_worker_code], create_pyproxies=False), + _obj_from_dict({"type": "application/javascript"}), + ) + + def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: + def onMsg(e: JsProxy) -> None: + self.streaming_ready = True + js_resolve_fn(e) + + def onErr(e: JsProxy) -> None: + js_reject_fn(e) # Defensive: never happens in ci + + self.js_worker.onmessage = onMsg + self.js_worker.onerror = onErr + + js_data_url = js.URL.createObjectURL(js_data_blob) + self.js_worker = js.globalThis.Worker.new(js_data_url) + self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) + + def send(self, request: EmscriptenRequest) -> EmscriptenResponse: + headers = { + k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE + } + + body = request.body + fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} + # start the request off in the worker + timeout = int(1000 * request.timeout) if request.timeout > 0 else None + js_shared_buffer = js.SharedArrayBuffer.new(1048576) + js_int_buffer = js.Int32Array.new(js_shared_buffer) + js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) + + js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) + js.Atomics.notify(js_int_buffer, 0) + js_absolute_url = js.URL.new(request.url, js.location).href + self.js_worker.postMessage( + _obj_from_dict( + { + "buffer": js_shared_buffer, + "url": js_absolute_url, + "fetchParams": fetch_data, + } + ) + ) + # wait for the worker to send something + js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) + if js_int_buffer[0] == ERROR_TIMEOUT: + raise _TimeoutError( + "Timeout connecting to streaming request", + request=request, + response=None, + ) + elif js_int_buffer[0] == SUCCESS_HEADER: + # got response + # header length is in second int of intBuffer + string_len = js_int_buffer[1] + # decode the rest to a JSON string + js_decoder = js.TextDecoder.new() + # this does a copy (the slice) because decode can't work on shared array + # for some silly reason + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + # get it as an object + response_obj = json.loads(json_str) + return EmscriptenResponse( + request=request, + status_code=response_obj["status"], + headers=response_obj["headers"], + body=_ReadStream( + js_int_buffer, + js_byte_buffer, + request.timeout, + self.js_worker, + response_obj["connectionID"], + request, + ), + ) + elif js_int_buffer[0] == ERROR_EXCEPTION: + string_len = js_int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", request=request, response=None + ) + else: + raise _StreamingError( + f"Unknown status from worker in fetch: {js_int_buffer[0]}", + request=request, + response=None, + ) + + +class _JSPIReadStream(io.RawIOBase): + """ + A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch + response. This requires support for WebAssembly JavaScript Promise Integration + in the containing browser, and for pyodide to be launched via runPythonAsync. + + :param js_read_stream: + The JavaScript stream reader + + :param timeout: + Timeout in seconds + + :param request: + The request we're handling + + :param response: + The response this stream relates to + + :param js_abort_controller: + A JavaScript AbortController object, used for timeouts + """ + + def __init__( + self, + js_read_stream: Any, + timeout: float, + request: EmscriptenRequest, + response: EmscriptenResponse, + js_abort_controller: Any, # JavaScript AbortController for timeouts + ): + self.js_read_stream = js_read_stream + self.timeout = timeout + self._is_closed = False + self._is_done = False + self.request: EmscriptenRequest | None = request + self.response: EmscriptenResponse | None = response + self.current_buffer = None + self.current_buffer_pos = 0 + self.js_abort_controller = js_abort_controller + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.js_read_stream.cancel() + self.js_read_stream = None + self._is_closed = True + self._is_done = True + self.request = None + self.response = None + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def _get_next_buffer(self) -> bool: + result_js = _run_sync_with_timeout( + self.js_read_stream.read(), + self.timeout, + self.js_abort_controller, + request=self.request, + response=self.response, + ) + if result_js.done: + self._is_done = True + return False + else: + self.current_buffer = result_js.value.to_py() + self.current_buffer_pos = 0 + return True + + def readinto(self, byte_obj: Buffer) -> int: + if self.current_buffer is None: + if not self._get_next_buffer() or self.current_buffer is None: + self.close() + return 0 + ret_length = min( + len(byte_obj), len(self.current_buffer) - self.current_buffer_pos + ) + byte_obj[0:ret_length] = self.current_buffer[ + self.current_buffer_pos : self.current_buffer_pos + ret_length + ] + self.current_buffer_pos += ret_length + if self.current_buffer_pos == len(self.current_buffer): + self.current_buffer = None + return ret_length + + +# check if we are in a worker or not +def is_in_browser_main_thread() -> bool: + return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window + + +def is_cross_origin_isolated() -> bool: + return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated + + +def is_in_node() -> bool: + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + and hasattr(js.process.release, "name") + and js.process.release.name == "node" + ) + + +def is_worker_available() -> bool: + return hasattr(js, "Worker") and hasattr(js, "Blob") + + +_fetcher: _StreamingFetcher | None = None + +if is_worker_available() and ( + (is_cross_origin_isolated() and not is_in_browser_main_thread()) + and (not is_in_node()) +): + _fetcher = _StreamingFetcher() +else: + _fetcher = None + + +NODE_JSPI_ERROR = ( + "urllib3 only works in Node.js with pyodide.runPythonAsync" + " and requires the flag --experimental-wasm-stack-switching in " + " versions of node <24." +) + + +def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: + if has_jspi(): + return send_jspi_request(request, True) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + + if _fetcher and streaming_ready(): + return _fetcher.send(request) + else: + _show_streaming_warning() + return None + + +_SHOWN_TIMEOUT_WARNING = False + + +def _show_timeout_warning() -> None: + global _SHOWN_TIMEOUT_WARNING + if not _SHOWN_TIMEOUT_WARNING: + _SHOWN_TIMEOUT_WARNING = True + message = "Warning: Timeout is not available on main browser thread" + js.console.warn(message) + + +_SHOWN_STREAMING_WARNING = False + + +def _show_streaming_warning() -> None: + global _SHOWN_STREAMING_WARNING + if not _SHOWN_STREAMING_WARNING: + _SHOWN_STREAMING_WARNING = True + message = "Can't stream HTTP requests because: \n" + if not is_cross_origin_isolated(): + message += " Page is not cross-origin isolated\n" + if is_in_browser_main_thread(): + message += " Python is running in main browser thread\n" + if not is_worker_available(): + message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in + if streaming_ready() is False: + message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch +is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" + from js import console + + console.warn(message) + + +def send_request(request: EmscriptenRequest) -> EmscriptenResponse: + if has_jspi(): + return send_jspi_request(request, False) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + try: + js_xhr = js.XMLHttpRequest.new() + + if not is_in_browser_main_thread(): + js_xhr.responseType = "arraybuffer" + if request.timeout: + js_xhr.timeout = int(request.timeout * 1000) + else: + js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") + if request.timeout: + # timeout isn't available on the main thread - show a warning in console + # if it is set + _show_timeout_warning() + + js_xhr.open(request.method, request.url, False) + for name, value in request.headers.items(): + if name.lower() not in HEADERS_TO_IGNORE: + js_xhr.setRequestHeader(name, value) + + js_xhr.send(to_js(request.body)) + + headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) + + if not is_in_browser_main_thread(): + body = js_xhr.response.to_py().tobytes() + else: + body = js_xhr.response.encode("ISO-8859-15") + return EmscriptenResponse( + status_code=js_xhr.status, headers=headers, body=body, request=request + ) + except JsException as err: + if err.name == "TimeoutError": + raise _TimeoutError(err.message, request=request) + elif err.name == "NetworkError": + raise _RequestError(err.message, request=request) + else: + # general http error + raise _RequestError(err.message, request=request) + + +def send_jspi_request( + request: EmscriptenRequest, streaming: bool +) -> EmscriptenResponse: + """ + Send a request using WebAssembly JavaScript Promise Integration + to wrap the asynchronous JavaScript fetch api (experimental). + + :param request: + Request to send + + :param streaming: + Whether to stream the response + + :return: The response object + :rtype: EmscriptenResponse + """ + timeout = request.timeout + js_abort_controller = js.AbortController.new() + headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} + req_body = request.body + fetch_data = { + "headers": headers, + "body": to_js(req_body), + "method": request.method, + "signal": js_abort_controller.signal, + } + # Node.js returns the whole response (unlike opaqueredirect in browsers), + # so urllib3 can set `redirect: manual` to control redirects itself. + # https://stackoverflow.com/a/78524615 + if _is_node_js(): + fetch_data["redirect"] = "manual" + # Call JavaScript fetch (async api, returns a promise) + fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) + # Now suspend WebAssembly until we resolve that promise + # or time out. + response_js = _run_sync_with_timeout( + fetcher_promise_js, + timeout, + js_abort_controller, + request=request, + response=None, + ) + headers = {} + header_iter = response_js.headers.entries() + while True: + iter_value_js = header_iter.next() + if getattr(iter_value_js, "done", False): + break + else: + headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) + status_code = response_js.status + body: bytes | io.RawIOBase = b"" + + response = EmscriptenResponse( + status_code=status_code, headers=headers, body=b"", request=request + ) + if streaming: + # get via inputstream + if response_js.body is not None: + # get a reader from the fetch response + body_stream_js = response_js.body.getReader() + body = _JSPIReadStream( + body_stream_js, timeout, request, response, js_abort_controller + ) + else: + # get directly via arraybuffer + # n.b. this is another async JavaScript call. + body = _run_sync_with_timeout( + response_js.arrayBuffer(), + timeout, + js_abort_controller, + request=request, + response=response, + ).to_py() + response.body = body + return response + + +def _run_sync_with_timeout( + promise: Any, + timeout: float, + js_abort_controller: Any, + request: EmscriptenRequest | None, + response: EmscriptenResponse | None, +) -> Any: + """ + Await a JavaScript promise synchronously with a timeout which is implemented + via the AbortController + + :param promise: + Javascript promise to await + + :param timeout: + Timeout in seconds + + :param js_abort_controller: + A JavaScript AbortController object, used on timeout + + :param request: + The request being handled + + :param response: + The response being handled (if it exists yet) + + :raises _TimeoutError: If the request times out + :raises _RequestError: If the request raises a JavaScript exception + + :return: The result of awaiting the promise. + """ + timer_id = None + if timeout > 0: + timer_id = js.setTimeout( + js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) + ) + try: + from pyodide.ffi import run_sync + + # run_sync here uses WebAssembly JavaScript Promise Integration to + # suspend python until the JavaScript promise resolves. + return run_sync(promise) + except JsException as err: + if err.name == "AbortError": + raise _TimeoutError( + message="Request timed out", request=request, response=response + ) + else: + raise _RequestError(message=err.message, request=request, response=response) + finally: + if timer_id is not None: + js.clearTimeout(timer_id) + + +def has_jspi() -> bool: + """ + Return true if jspi can be used. + + This requires both browser support and also WebAssembly + to be in the correct state - i.e. that the javascript + call into python was async not sync. + + :return: True if jspi can be used. + :rtype: bool + """ + try: + from pyodide.ffi import can_run_sync, run_sync # noqa: F401 + + return bool(can_run_sync()) + except ImportError: + return False + + +def _is_node_js() -> bool: + """ + Check if we are in Node.js. + + :return: True if we are in Node.js. + :rtype: bool + """ + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + # According to the Node.js documentation, the release name is always "node". + and js.process.release.name == "node" + ) + + +def streaming_ready() -> bool | None: + if _fetcher: + return _fetcher.streaming_ready + else: + return None # no fetcher, return None to signify that + + +async def wait_for_streaming_ready() -> bool: + if _fetcher: + await _fetcher.js_worker_ready_promise + return True + else: + return False diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/request.py b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/response.py b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1e1dbe83722c5fb16290a852859252ae616826 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,281 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._uncached_read_occurred = False + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + version_string="HTTP/?", + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None and amt >= 0: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + self._uncached_read_occurred = True + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content and not self._uncached_read_occurred: + self._body = data + else: + self._uncached_read_occurred = True + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/pyopenssl.py b/python/user_packages/Python313/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 0000000000000000000000000000000000000000..f06b8599920fdcf6b8a2f869141378709a30c84c --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,563 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 19.0.0) +* `cryptography`_ (minimum 2.3, from pyopenssl) +* `idna`_ (minimum 2.1, from cryptography) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL # type: ignore[import-not-found] +from cryptography import x509 + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from io import BytesIO +from socket import socket as socket_cls + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 # type: ignore[import-not-found] + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, +} + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data # type: ignore[no-any-return] + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise TimeoutError("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) # type: ignore[no-any-return] + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise TimeoutError() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self, how: int) -> None: + try: + self.connection.shutdown() + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"shutdown error: {e!r}") from e + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | None: + x509 = self.connection.get_peer_certificate() + + if not x509: + return x509 # type: ignore[no-any-return] + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return] + + return { + "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() # type: ignore[no-any-return] + + def selected_alpn_protocol(self) -> str | None: + alpn_proto = self.connection.get_alpn_proto_negotiated() + return alpn_proto.decode() if alpn_proto else None + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_flags(self) -> int: + return self._verify_flags + + @verify_flags.setter + def verify_flags(self, value: int) -> None: + self._verify_flags = value + self._ctx.get_cert_store().set_flags(self._verify_flags) + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(BytesIO(cadata)) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") # type: ignore[assignment] + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise TimeoutError("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/python/user_packages/Python313/site-packages/urllib3/contrib/socks.py b/python/user_packages/Python313/site-packages/urllib3/contrib/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..d37da8fc2049a7b3f7e18d2f64e79c205cfe3d3e --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,228 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks # type: ignore[import-untyped] +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +class _TYPE_SOCKS_OPTIONS(typing.TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: # Defensive: see https://github.com/urllib3/urllib3/pull/3728#pullrequestreview-3816302703 + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None and parsed.auth is not None: + split = parsed.auth.split(":") + if len(split) == 2: + username, password = split + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/__init__.py b/python/user_packages/Python313/site-packages/urllib3/http2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..133e1d8f237f6fddd557ae1c0e0cf738f7cc2748 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/http2/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from importlib.metadata import version + +__all__ = [ + "inject_into_urllib3", + "extract_from_urllib3", +] + +import typing + +orig_HTTPSConnection: typing.Any = None + + +def inject_into_urllib3() -> None: + # First check if h2 version is valid + h2_version = version("h2") + if not h2_version.startswith("4."): + raise ImportError( + "urllib3 v2 supports h2 version 4.x.x, currently " + f"the 'h2' module is compiled with {h2_version!r}. " + "See: https://github.com/urllib3/urllib3/issues/3290" + ) + + # Import here to avoid circular dependencies. + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + from .connection import HTTP2Connection + + global orig_HTTPSConnection + orig_HTTPSConnection = urllib3_connection.HTTPSConnection + + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3_util.ALPN_PROTOCOLS = ["h2"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3_util.ALPN_PROTOCOLS = ["http/1.1"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"] diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc4dbadb0fb4baf6affac310599415b9c65023ad Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ae9f357339a3c538c42e99cdc2cc35a554dba42 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/probe.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/probe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33cc5e39aa310cbbec54d64935be24b4b5947d92 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/http2/__pycache__/probe.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/connection.py b/python/user_packages/Python313/site-packages/urllib3/http2/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..0a026da0a8357e324ded47b82b24042713b9bf06 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/http2/connection.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +import logging +import re +import threading +import types +import typing + +import h2.config +import h2.connection +import h2.events + +from .._base_connection import _TYPE_BODY +from .._collections import HTTPHeaderDict +from ..connection import HTTPSConnection, _get_default_user_agent +from ..exceptions import ConnectionError +from ..response import BaseHTTPResponse + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + +log = logging.getLogger(__name__) + +RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$") +RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$") + + +def _is_legal_header_name(name: bytes) -> bool: + """ + "An implementation that validates fields according to the definitions in Sections + 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not + include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + + `http.client._is_legal_header_name` does not validate the field name according to the + HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters. + + This does not allow for the `:` character in the header name, so should not + be used to validate pseudo-headers. + """ + return bool(RE_IS_LEGAL_HEADER_NAME.match(name)) + + +def _is_illegal_header_value(value: bytes) -> bool: + """ + "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed + (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field + value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, + 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + """ + return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value)) + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + __slots__ = ( + "lock", + "_obj", + ) + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + if self._tunnel_host is not None: + raise NotImplementedError("Tunneling isn't supported with HTTP/2") + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + with self._h2_conn as conn: + conn.initiate_connection() + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + def putrequest( # type: ignore[override] + self, + method: str, + url: str, + **kwargs: typing.Any, + ) -> None: + """putrequest + This deviates from the HTTPConnection method signature since we never need to override + sending accept-encoding headers or the host header. + """ + if "skip_host" in kwargs: + raise NotImplementedError("`skip_host` isn't supported") + if "skip_accept_encoding" in kwargs: + raise NotImplementedError("`skip_accept_encoding` isn't supported") + + self._request_url = url or "/" + self._validate_path(url) # type: ignore[attr-defined] + + if ":" in self.host: + authority = f"[{self.host}]:{self.port or 443}" + else: + authority = f"{self.host}:{self.port or 443}" + + self._headers.append((b":scheme", b"https")) + self._headers.append((b":method", method.encode())) + self._headers.append((b":authority", authority.encode())) + self._headers.append((b":path", url.encode())) + + with self._h2_conn as conn: + self._h2_stream = conn.get_next_available_stream_id() + + def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override] + # TODO SKIPPABLE_HEADERS from urllib3 are ignored. + header = header.encode() if isinstance(header, str) else header + header = header.lower() # A lot of upstream code uses capitalized headers. + if not _is_legal_header_name(header): + raise ValueError(f"Illegal header name {str(header)}") + + for value in values: + value = value.encode() if isinstance(value, str) else value + if _is_illegal_header_value(value): + raise ValueError(f"Illegal header value {str(value)}") + self._headers.append((header, value)) + + def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override] + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + conn.send_headers( + stream_id=self._h2_stream, + headers=self._headers, + end_stream=(message_body is None), + ) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + self._headers = [] # Reset headers for the next request. + + def send(self, data: typing.Any) -> None: + """Send data to the server. + `data` can be: `str`, `bytes`, an iterable, or file-like objects + that support a .read() method. + """ + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + if hasattr(data, "read"): # file-like objects + while True: + chunk = data.read(self.blocksize) + if not chunk: + break + if isinstance(chunk, str): + chunk = chunk.encode() + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + return + + if isinstance(data, str): # str -> bytes + data = data.encode() + + try: + if isinstance(data, bytes): + conn.send_data(self._h2_stream, data, end_stream=True) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + else: + for chunk in data: + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + except TypeError: + raise TypeError( + "`data` should be str, bytes, iterable, or file. got %r" + % type(data) + ) + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + raise NotImplementedError( + "HTTP/2 does not support setting up a tunnel through a proxy" + ) + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + **kwargs: typing.Any, + ) -> None: + """Send an HTTP/2 request""" + if "chunked" in kwargs: + # TODO this is often present from upstream. + # raise NotImplementedError("`chunked` isn't supported with HTTP/2") + pass + + if self.sock is not None: + self.sock.settimeout(self.timeout) + + self.putrequest(method, url) + + headers = headers or {} + for k, v in headers.items(): + if k.lower() == "transfer-encoding" and v == "chunked": + continue + else: + self.putheader(k, v) + + if b"user-agent" not in dict(self._headers): + self.putheader(b"user-agent", _get_default_user_agent()) + + if body: + self.endheaders(message_body=body) + self.send(body) + else: + self.endheaders() + + def close(self) -> None: + with self._h2_conn as conn: + try: + conn.close_connection() + if data := conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + version_string="HTTP/2", + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass diff --git a/python/user_packages/Python313/site-packages/urllib3/http2/probe.py b/python/user_packages/Python313/site-packages/urllib3/http2/probe.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea900764f0885eafaac9454523417d86e33df2d --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/http2/probe.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import threading + + +class _HTTP2ProbeCache: + __slots__ = ( + "_lock", + "_cache_locks", + "_cache_values", + ) + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cache_locks: dict[tuple[str, int], threading.RLock] = {} + self._cache_values: dict[tuple[str, int], bool | None] = {} + + def acquire_and_get(self, host: str, port: int) -> bool | None: + # By the end of this block we know that + # _cache_[values,locks] is available. + value = None + with self._lock: + key = (host, port) + try: + value = self._cache_values[key] + # If it's a known value we return right away. + if value is not None: + return value + except KeyError: + self._cache_locks[key] = threading.RLock() + self._cache_values[key] = None + + # If the value is unknown, we acquire the lock to signal + # to the requesting thread that the probe is in progress + # or that the current thread needs to return their findings. + key_lock = self._cache_locks[key] + key_lock.acquire() + try: + # If the by the time we get the lock the value has been + # updated we want to return the updated value. + value = self._cache_values[key] + + # In case an exception like KeyboardInterrupt is raised here. + except BaseException as e: # Defensive: + assert not isinstance(e, KeyError) # KeyError shouldn't be possible. + key_lock.release() + raise + + return value + + def set_and_release( + self, host: str, port: int, supports_http2: bool | None + ) -> None: + key = (host, port) + key_lock = self._cache_locks[key] + with key_lock: # Uses an RLock, so can be locked again from same thread. + if supports_http2 is None and self._cache_values[key] is not None: + raise ValueError( + "Cannot reset HTTP/2 support for origin after value has been set." + ) # Defensive: not expected in normal usage + + self._cache_values[key] = supports_http2 + key_lock.release() + + def _values(self) -> dict[tuple[str, int], bool | None]: + """This function is for testing purposes only. Gets the current state of the probe cache""" + with self._lock: + return {k: v for k, v in self._cache_values.items()} + + def _reset(self) -> None: + """This function is for testing purposes only. Reset the cache values""" + with self._lock: + self._cache_locks = {} + self._cache_values = {} + + +_HTTP2_PROBE_CACHE = _HTTP2ProbeCache() + +set_and_release = _HTTP2_PROBE_CACHE.set_and_release +acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get +_values = _HTTP2_PROBE_CACHE._values +_reset = _HTTP2_PROBE_CACHE._reset + +__all__ = [ + "set_and_release", + "acquire_and_get", +] diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__init__.py b/python/user_packages/Python313/site-packages/urllib3/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..534126033c083203649022fa9b753a433f005556 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/__init__.py @@ -0,0 +1,42 @@ +# For backwards compatibility, provide imports that used to be here. +from __future__ import annotations + +from .connection import is_connection_dropped +from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers +from .response import is_fp_closed +from .retry import Retry +from .ssl_ import ( + ALPN_PROTOCOLS, + IS_PYOPENSSL, + SSLContext, + assert_fingerprint, + create_urllib3_context, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .timeout import Timeout +from .url import Url, parse_url +from .wait import wait_for_read, wait_for_write + +__all__ = ( + "IS_PYOPENSSL", + "SSLContext", + "ALPN_PROTOCOLS", + "Retry", + "Timeout", + "Url", + "assert_fingerprint", + "create_urllib3_context", + "is_connection_dropped", + "is_fp_closed", + "parse_url", + "make_headers", + "resolve_cert_reqs", + "resolve_ssl_version", + "ssl_wrap_socket", + "wait_for_read", + "wait_for_write", + "SKIP_HEADER", + "SKIPPABLE_HEADERS", +) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed4c1d64d404b468cfbaffe8a514a46bdf8202b5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/connection.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a63a4c43e2d60a4475401f2a9360a460b8f61f96 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/connection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/proxy.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/proxy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b4de8e52379889eac6e2fdd935b42da2124f32f Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/proxy.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/request.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/request.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08c3369c4d067523043c30377e0f524ab971aaa1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/request.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/response.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/response.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45efef987dd98bc0ee6fefbb7aa178bc3b97437a Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/response.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/retry.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/retry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15e30d414edbf75290420092af47a29de633e3bb Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/retry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6f896e7429be47d7ab41f583532f3c7a9ea5bd0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b17096c1882edff7a678ae02e5ed68ca90f23f4a Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssltransport.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssltransport.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fd19df37d29b93a5d0c44e3b249602b50585bd9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/ssltransport.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/timeout.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/timeout.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35e4449086e75ec4cefa92429ee9ad41c4ebb84e Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/timeout.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/url.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/url.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69f81e34a2db3281120e7ea6b250843584ade2c8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/url.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad771436447826482169c8cb073c5000988ff707 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/wait.cpython-313.pyc b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/wait.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b52283f38c04312a2d273bd812a43f8cdf5c1e9f Binary files /dev/null and b/python/user_packages/Python313/site-packages/urllib3/util/__pycache__/wait.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urllib3/util/connection.py b/python/user_packages/Python313/site-packages/urllib3/util/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f92519ee9124e91e5da7d60ccc3f274312ed3514 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/connection.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import socket +import typing + +from ..exceptions import LocationParseError +from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT + +_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]] + +if typing.TYPE_CHECKING: + from .._base_connection import BaseHTTPConnection + + +def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific + """ + Returns True if the connection is dropped and should be closed. + :param conn: :class:`urllib3.connection.HTTPConnection` object. + """ + return not conn.is_connected + + +# This function is copied from socket.py in the Python 2.7 standard +# library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. +def create_connection( + address: tuple[str, int], + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, +) -> socket.socket: + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`socket.getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + """ + + host, port = address + if host.startswith("["): + host = host.strip("[]") + err = None + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + try: + host.encode("idna") + except UnicodeError: + raise LocationParseError(f"'{host}', label empty or too long") from None + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + + # If provided, set socket level options before connecting. + _set_socket_options(sock, socket_options) + + if timeout is not _DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + # Break explicitly a reference cycle + err = None + return sock + + except OSError as _: + err = _ + if sock is not None: + sock.close() + + if err is not None: + try: + raise err + finally: + # Break explicitly a reference cycle + err = None + else: + raise OSError("getaddrinfo returns an empty list") + + +def _set_socket_options( + sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None +) -> None: + if options is None: + return + + for opt in options: + sock.setsockopt(*opt) + + +def allowed_gai_family() -> socket.AddressFamily: + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host: str) -> bool: + """Returns True if the system can bind an IPv6 address.""" + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/urllib3/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + + +HAS_IPV6 = _has_ipv6("::1") diff --git a/python/user_packages/Python313/site-packages/urllib3/util/proxy.py b/python/user_packages/Python313/site-packages/urllib3/util/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..908fc6621d0afbed16bde2c1957a5cf28d3a84d8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/proxy.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .url import Url + +if typing.TYPE_CHECKING: + from ..connection import ProxyConfig + + +def connection_requires_http_tunnel( + proxy_url: Url | None = None, + proxy_config: ProxyConfig | None = None, + destination_scheme: str | None = None, +) -> bool: + """ + Returns True if the connection requires an HTTP CONNECT through the proxy. + + :param URL proxy_url: + URL of the proxy. + :param ProxyConfig proxy_config: + Proxy configuration from poolmanager.py + :param str destination_scheme: + The scheme of the destination. (i.e https, http, etc) + """ + # If we're not using a proxy, no way to use a tunnel. + if proxy_url is None: + return False + + # HTTP destinations never require tunneling, we always forward. + if destination_scheme == "http": + return False + + # Support for forwarding with HTTPS proxies and HTTPS destinations. + if ( + proxy_url.scheme == "https" + and proxy_config + and proxy_config.use_forwarding_for_https + ): + return False + + # Otherwise always use a tunnel. + return True diff --git a/python/user_packages/Python313/site-packages/urllib3/util/request.py b/python/user_packages/Python313/site-packages/urllib3/util/request.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2372ba7e777826a4eb124ddfb54f0240b65d67 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/request.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import io +import sys +import typing +from base64 import b64encode +from enum import Enum + +from ..exceptions import UnrewindableBodyError +from .util import to_bytes + +if typing.TYPE_CHECKING: + from typing import Final + +# Pass as a value within ``headers`` to skip +# emitting some HTTP headers that are added automatically. +# The only headers that are supported are ``Accept-Encoding``, +# ``Host``, and ``User-Agent``. +SKIP_HEADER = "@@@SKIP_HEADER@@@" +SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) + +ACCEPT_ENCODING = "gzip,deflate" +try: + try: + import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 + except ImportError: + import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",br" + +try: + if sys.version_info >= (3, 14): + from compression import zstd as _unused_module_zstd # noqa: F401 + else: + from backports import zstd as _unused_module_zstd # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",zstd" + + +class _TYPE_FAILEDTELL(Enum): + token = 0 + + +_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token + +_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL] + +# When sending a request with these methods we aren't expecting +# a body so don't need to set an explicit 'Content-Length: 0' +# The reason we do this in the negative instead of tracking methods +# which 'should' have a body is because unknown methods should be +# treated as if they were 'POST' which *does* expect a body. +_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"} + + +def make_headers( + keep_alive: bool | None = None, + accept_encoding: bool | list[str] | str | None = None, + user_agent: str | None = None, + basic_auth: str | None = None, + proxy_basic_auth: str | None = None, + disable_cache: bool | None = None, +) -> dict[str, str]: + """ + Shortcuts for generating request headers. + + :param keep_alive: + If ``True``, adds 'connection: keep-alive' header. + + :param accept_encoding: + Can be a boolean, list, or string. + ``True`` translates to 'gzip,deflate'. If the dependencies for + Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or + Zstandard (the ``backports.zstd`` package for Python before 3.14) + algorithms are installed, then their encodings are + included in the string ('br' and 'zstd', respectively). + List will get joined by comma. + String will be used as provided. + + :param user_agent: + String representing the user-agent you want, such as + "python-urllib3/0.6" + + :param basic_auth: + Colon-separated username:password string for 'authorization: basic ...' + auth header. + + :param proxy_basic_auth: + Colon-separated username:password string for 'proxy-authorization: basic ...' + auth header. + + :param disable_cache: + If ``True``, adds 'cache-control: no-cache' header. + + Example: + + .. code-block:: python + + import urllib3 + + print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0")) + # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} + print(urllib3.util.make_headers(accept_encoding=True)) + # {'accept-encoding': 'gzip,deflate'} + """ + headers: dict[str, str] = {} + if accept_encoding: + if isinstance(accept_encoding, str): + pass + elif isinstance(accept_encoding, list): + accept_encoding = ",".join(accept_encoding) + else: + accept_encoding = ACCEPT_ENCODING + headers["accept-encoding"] = accept_encoding + + if user_agent: + headers["user-agent"] = user_agent + + if keep_alive: + headers["connection"] = "keep-alive" + + if basic_auth: + headers["authorization"] = ( + f"Basic {b64encode(basic_auth.encode('latin-1')).decode()}" + ) + + if proxy_basic_auth: + headers["proxy-authorization"] = ( + f"Basic {b64encode(proxy_basic_auth.encode('latin-1')).decode()}" + ) + + if disable_cache: + headers["cache-control"] = "no-cache" + + return headers + + +def set_file_position( + body: typing.Any, pos: _TYPE_BODY_POSITION | None +) -> _TYPE_BODY_POSITION | None: + """ + If a position is provided, move file to that point. + Otherwise, we'll attempt to record a position for future use. + """ + if pos is not None: + rewind_body(body, pos) + elif getattr(body, "tell", None) is not None: + try: + pos = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body. + pos = _FAILEDTELL + + return pos + + +def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None: + """ + Attempt to rewind body to a certain position. + Primarily used for request redirects and retries. + + :param body: + File-like object that supports seek. + + :param int pos: + Position to seek to in file. + """ + body_seek = getattr(body, "seek", None) + if body_seek is not None and isinstance(body_pos, int): + try: + body_seek(body_pos) + except OSError as e: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect/retry." + ) from e + elif body_pos is _FAILEDTELL: + raise UnrewindableBodyError( + "Unable to record file position for rewinding " + "request body during a redirect/retry." + ) + else: + raise ValueError( + f"body_pos must be of type integer, instead it was {type(body_pos)}." + ) + + +class ChunksAndContentLength(typing.NamedTuple): + chunks: typing.Iterable[bytes] | None + content_length: int | None + + +def body_to_chunks( + body: typing.Any | None, method: str, blocksize: int +) -> ChunksAndContentLength: + """Takes the HTTP request method, body, and blocksize and + transforms them into an iterable of chunks to pass to + socket.sendall() and an optional 'Content-Length' header. + + A 'Content-Length' of 'None' indicates the length of the body + can't be determined so should use 'Transfer-Encoding: chunked' + for framing instead. + """ + + chunks: typing.Iterable[bytes] | None + content_length: int | None + + # No body, we need to make a recommendation on 'Content-Length' + # based on whether that request method is expected to have + # a body or not. + if body is None: + chunks = None + if method.upper() not in _METHODS_NOT_EXPECTING_BODY: + content_length = 0 + else: + content_length = None + + # Bytes or strings become bytes + elif isinstance(body, (str, bytes)): + chunks = (to_bytes(body),) + content_length = len(chunks[0]) + + # File-like object, TODO: use seek() and tell() for length? + elif hasattr(body, "read"): + + def chunk_readable() -> typing.Iterable[bytes]: + encode = isinstance(body, io.TextIOBase) + while True: + datablock = body.read(blocksize) + if not datablock: + break + if encode: + datablock = datablock.encode("utf-8") + yield datablock + + chunks = chunk_readable() + content_length = None + + # Otherwise we need to start checking via duck-typing. + else: + try: + # Check if the body implements the buffer API. + mv = memoryview(body) + except TypeError: + try: + # Check if the body is an iterable + chunks = iter(body) + content_length = None + except TypeError: + raise TypeError( + f"'body' must be a bytes-like object, file-like " + f"object, or iterable. Instead was {body!r}" + ) from None + else: + # Since it implements the buffer API can be passed directly to socket.sendall() + chunks = (body,) + content_length = mv.nbytes + + return ChunksAndContentLength(chunks=chunks, content_length=content_length) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/response.py b/python/user_packages/Python313/site-packages/urllib3/util/response.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4578696fa2e17a900c6890ec26d65e860b0b72 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/response.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import http.client as httplib +from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj: object) -> bool: + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check `isclosed()` first, in case Python3 doesn't set `closed`. + # GH Issue #928 + return obj.isclosed() # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check via the official file-like-object way. + return obj.closed # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None # type: ignore[attr-defined] + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers: httplib.HTTPMessage) -> None: + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param http.client.HTTPMessage headers: Headers to verify. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError(f"expected httplib.Message, got {type(headers)}.") + + unparsed_data = None + + # get_payload is actually email.message.Message.get_payload; + # we're only interested in the result if it's not a multipart message + if not headers.is_multipart(): + payload = headers.get_payload() + + if isinstance(payload, (bytes, str)): + unparsed_data = payload + + # httplib is assuming a response body is available + # when parsing headers even when httplib only sends + # header data to parse_headers() This results in + # defects on multipart responses in particular. + # See: https://github.com/urllib3/urllib3/issues/800 + + # So we ignore the following defects: + # - StartBoundaryNotFoundDefect: + # The claimed start boundary was never found. + # - MultipartInvariantViolationDefect: + # A message claimed to be a multipart but no subparts were found. + defects = [ + defect + for defect in headers.defects + if not isinstance( + defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) + ) + ] + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response: httplib.HTTPResponse) -> bool: + """ + Checks whether the request of a response has been a HEAD-request. + + :param http.client.HTTPResponse response: + Response to check if the originating request + used 'HEAD' as a method. + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method_str = response._method # type: str # type: ignore[attr-defined] + return method_str.upper() == "HEAD" diff --git a/python/user_packages/Python313/site-packages/urllib3/util/retry.py b/python/user_packages/Python313/site-packages/urllib3/util/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..7649898e1d9930724a456c1c6fdecb66e078b4cc --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/retry.py @@ -0,0 +1,557 @@ +from __future__ import annotations + +import email +import logging +import random +import re +import time +import typing +from itertools import takewhile +from types import TracebackType + +from ..exceptions import ( + ConnectTimeoutError, + InvalidHeader, + MaxRetryError, + ProtocolError, + ProxyError, + ReadTimeoutError, + ResponseError, +) +from .util import reraise + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from ..connectionpool import ConnectionPool + from ..response import BaseHTTPResponse + +log = logging.getLogger(__name__) + + +# Data structure for representing the metadata of requests that result in a retry. +class RequestHistory(typing.NamedTuple): + method: str | None + url: str | None + error: Exception | None + status: int | None + redirect_location: str | None + + +class Retry: + """Retry configuration. + + Each retry attempt will create a new Retry object with updated values, so + they can be safely reused. + + Retries can be defined as a default for a pool: + + .. code-block:: python + + retries = Retry(connect=5, read=2, redirect=5) + http = PoolManager(retries=retries) + response = http.request("GET", "https://example.com/") + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=Retry(10)) + + Retries can be disabled by passing ``False``: + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=False) + + Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless + retries are disabled, in which case the causing exception will be raised. + + :param int total: + Total number of retries to allow. Takes precedence over other counts. + + Set to ``None`` to remove this constraint and fall back on other + counts. + + Set to ``0`` to fail on the first retry. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int connect: + How many connection-related errors to retry on. + + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. + + Set to ``0`` to fail on the first retry of this type. + + :param int read: + How many times to retry on read errors. + + These errors are raised after the request was sent to the server, so the + request may have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + :param int redirect: + How many redirects to perform. Limit this to avoid infinite redirect + loops. + + A redirect is a HTTP response with a status code 301, 302, 303, 307 or + 308. + + Set to ``0`` to fail on the first retry of this type. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int status: + How many times to retry on bad status codes. + + These are retries made on responses, where status code matches + ``status_forcelist``. + + Set to ``0`` to fail on the first retry of this type. + + :param int other: + How many times to retry on other errors. + + Other errors are errors that are not connect, read, redirect or status errors. + These errors might be raised after the request was sent to the server, so the + request might have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + If ``total`` is not set, it's a good idea to set this to 0 to account + for unexpected edge cases and avoid infinite retry loops. + + :param Collection allowed_methods: + Set of uppercased HTTP method verbs that we should retry on. + + By default, we only retry on methods which are considered to be + idempotent (multiple requests with the same parameters end with the + same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. + + Set to a ``None`` value to retry on any verb. + + :param Collection status_forcelist: + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``allowed_methods`` + and the response status code is in ``status_forcelist``. + + By default, this is disabled with ``None``. + + :param float backoff_factor: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: + + {backoff factor} * (2 ** ({number of previous retries})) + + seconds. If `backoff_jitter` is non-zero, this sleep is extended by:: + + random.uniform(0, {backoff jitter}) + + seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will + sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever + be longer than `backoff_max`. + + By default, backoff is disabled (factor set to 0). + + :param float backoff_max: + The maximum backoff time (in seconds) between retry attempts. + This value caps the computed backoff from `backoff_factor`. + + :param float backoff_jitter: + Random jitter amount (in seconds) added to the computed backoff. + Jitter is sampled uniformly from `0` to `backoff_jitter`. + + :param bool raise_on_redirect: Whether, if the number of redirects is + exhausted, to raise a MaxRetryError, or to return a response with a + response code in the 3xx range. + + :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: + whether we should raise an exception, or return a response, + if status falls in ``status_forcelist`` range and retries have + been exhausted. + + :param tuple history: The history of the request encountered during + each call to :meth:`~Retry.increment`. The list is in the order + the requests occurred. Each list item is of class :class:`RequestHistory`. + + :param bool respect_retry_after_header: + Whether to respect Retry-After header on status codes defined as + :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. + + :param Collection remove_headers_on_redirect: + Sequence of headers to remove from the request when a response + indicating a redirect is returned before firing off the redirected + request. + + :param int retry_after_max: Number of seconds to allow as the maximum for + Retry-After headers. Defaults to :attr:`Retry.DEFAULT_RETRY_AFTER_MAX`. + Any Retry-After headers larger than this value will be limited to this + value. + """ + + #: Default methods to be used for ``allowed_methods`` + DEFAULT_ALLOWED_METHODS = frozenset( + ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] + ) + + #: Default status codes to be used for ``status_forcelist`` + RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) + + #: Default headers to be used for ``remove_headers_on_redirect`` + DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset( + ["Cookie", "Authorization", "Proxy-Authorization"] + ) + + #: Default maximum backoff time. + DEFAULT_BACKOFF_MAX = 120 + + # This is undocumented in the RFC. Setting to 6 hours matches other popular libraries. + #: Default maximum allowed value for Retry-After headers in seconds + DEFAULT_RETRY_AFTER_MAX: typing.Final[int] = 21600 + + # Backward compatibility; assigned outside of the class. + DEFAULT: typing.ClassVar[Retry] + + def __init__( + self, + total: bool | int | None = 10, + connect: int | None = None, + read: int | None = None, + redirect: bool | int | None = None, + status: int | None = None, + other: int | None = None, + allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS, + status_forcelist: typing.Collection[int] | None = None, + backoff_factor: float = 0, + backoff_max: float = DEFAULT_BACKOFF_MAX, + raise_on_redirect: bool = True, + raise_on_status: bool = True, + history: tuple[RequestHistory, ...] | None = None, + respect_retry_after_header: bool = True, + remove_headers_on_redirect: typing.Collection[ + str + ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT, + backoff_jitter: float = 0.0, + retry_after_max: int = DEFAULT_RETRY_AFTER_MAX, + ) -> None: + self.total = total + self.connect = connect + self.read = read + self.status = status + self.other = other + + if redirect is False or total is False: + redirect = 0 + raise_on_redirect = False + + self.redirect = redirect + self.status_forcelist = status_forcelist or set() + self.allowed_methods = allowed_methods + self.backoff_factor = backoff_factor + self.backoff_max = backoff_max + self.retry_after_max = retry_after_max + self.raise_on_redirect = raise_on_redirect + self.raise_on_status = raise_on_status + self.history = history or () + self.respect_retry_after_header = respect_retry_after_header + self.remove_headers_on_redirect = frozenset( + h.lower() for h in remove_headers_on_redirect + ) + self.backoff_jitter = backoff_jitter + + def new(self, **kw: typing.Any) -> Self: + params = dict( + total=self.total, + connect=self.connect, + read=self.read, + redirect=self.redirect, + status=self.status, + other=self.other, + allowed_methods=self.allowed_methods, + status_forcelist=self.status_forcelist, + backoff_factor=self.backoff_factor, + backoff_max=self.backoff_max, + retry_after_max=self.retry_after_max, + raise_on_redirect=self.raise_on_redirect, + raise_on_status=self.raise_on_status, + history=self.history, + remove_headers_on_redirect=self.remove_headers_on_redirect, + respect_retry_after_header=self.respect_retry_after_header, + backoff_jitter=self.backoff_jitter, + ) + + params.update(kw) + return type(self)(**params) # type: ignore[arg-type] + + @classmethod + def from_int( + cls, + retries: Retry | bool | int | None, + redirect: bool | int | None = True, + default: Retry | bool | int | None = None, + ) -> Retry: + """Backwards-compatibility for the old retries format.""" + if retries is None: + retries = default if default is not None else cls.DEFAULT + + if isinstance(retries, Retry): + return retries + + redirect = bool(redirect) and None + new_retries = cls(retries, redirect=redirect) + log.debug("Converted retries value: %r -> %r", retries, new_retries) + return new_retries + + def get_backoff_time(self) -> float: + """Formula for computing the current backoff + + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len( + list( + takewhile(lambda x: x.redirect_location is None, reversed(self.history)) + ) + ) + if consecutive_errors_len <= 1: + return 0 + + backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) + if self.backoff_jitter != 0.0: + backoff_value += random.random() * self.backoff_jitter + return float(max(0, min(self.backoff_max, backoff_value))) + + def parse_retry_after(self, retry_after: str) -> float: + seconds: float + # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = int(retry_after) + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + raise InvalidHeader(f"Invalid Retry-After header: {retry_after}") + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + seconds = max(seconds, 0) + + # Check the seconds do not exceed the specified maximum + if seconds > self.retry_after_max: + seconds = self.retry_after_max + + return seconds + + def get_retry_after(self, response: BaseHTTPResponse) -> float | None: + """Get the value of Retry-After in seconds.""" + + retry_after = response.headers.get("Retry-After") + + if retry_after is None: + return None + + return self.parse_retry_after(retry_after) + + def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: + retry_after = self.get_retry_after(response) + if retry_after: + time.sleep(retry_after) + return True + + return False + + def _sleep_backoff(self) -> None: + backoff = self.get_backoff_time() + if backoff <= 0: + return + time.sleep(backoff) + + def sleep(self, response: BaseHTTPResponse | None = None) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + """ + + if self.respect_retry_after_header and response: + slept = self.sleep_for_retry(response) + if slept: + return + + self._sleep_backoff() + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + """ + if isinstance(err, ProxyError): + err = err.original_error + return isinstance(err, ConnectTimeoutError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + """ + return isinstance(err, (ReadTimeoutError, ProtocolError)) + + def _is_method_retryable(self, method: str) -> bool: + """Checks if a given HTTP method should be retried upon, depending if + it is included in the allowed_methods + """ + if self.allowed_methods and method.upper() not in self.allowed_methods: + return False + return True + + def is_retry( + self, method: str, status_code: int, has_retry_after: bool = False + ) -> bool: + """Is this method/status code retryable? (Based on allowlists and control + variables such as the number of total retries to allow, whether to + respect the Retry-After header, whether this header is present, and + whether the returned status code is on the list of status codes to + be retried upon on the presence of the aforementioned header) + """ + if not self._is_method_retryable(method): + return False + + if self.status_forcelist and status_code in self.status_forcelist: + return True + + return bool( + self.total + and self.respect_retry_after_header + and has_retry_after + and (status_code in self.RETRY_AFTER_STATUS_CODES) + ) + + def is_exhausted(self) -> bool: + """Are we out of retries?""" + retry_counts = [ + x + for x in ( + self.total, + self.connect, + self.read, + self.redirect, + self.status, + self.other, + ) + if x + ] + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + method: str | None = None, + url: str | None = None, + response: BaseHTTPResponse | None = None, + error: Exception | None = None, + _pool: ConnectionPool | None = None, + _stacktrace: TracebackType | None = None, + ) -> Self: + """Return a new Retry object with incremented retry counters. + + :param response: A response object, or None, if the server did not + return a response. + :type response: :class:`~urllib3.response.BaseHTTPResponse` + :param Exception error: An error encountered during the request, or + None if the response was received successfully. + + :return: A new ``Retry`` object. + """ + if self.total is False and error: + # Disabled, indicate to re-raise the error. + raise reraise(type(error), error, _stacktrace) + + total = self.total + if total is not None: + total -= 1 + + connect = self.connect + read = self.read + redirect = self.redirect + status_count = self.status + other = self.other + cause = "unknown" + status = None + redirect_location = None + + if error and self._is_connection_error(error): + # Connect retry? + if connect is False: + raise reraise(type(error), error, _stacktrace) + elif connect is not None: + connect -= 1 + + elif error and self._is_read_error(error): + # Read retry? + if read is False or method is None or not self._is_method_retryable(method): + raise reraise(type(error), error, _stacktrace) + elif read is not None: + read -= 1 + + elif error: + # Other retry? + if other is not None: + other -= 1 + + elif response and response.get_redirect_location(): + # Redirect retry? + if redirect is not None: + redirect -= 1 + cause = "too many redirects" + response_redirect_location = response.get_redirect_location() + if response_redirect_location: + redirect_location = response_redirect_location + status = response.status + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowed_methods + cause = ResponseError.GENERIC_ERROR + if response and response.status: + if status_count is not None: + status_count -= 1 + cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) + status = response.status + + history = self.history + ( + RequestHistory(method, url, error, status, redirect_location), + ) + + new_retry = self.new( + total=total, + connect=connect, + read=read, + redirect=redirect, + status=status_count, + other=other, + history=history, + ) + + if new_retry.is_exhausted(): + reason = error or ResponseError(cause) + raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] + + log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) + + return new_retry + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(total={self.total}, connect={self.connect}, " + f"read={self.read}, redirect={self.redirect}, status={self.status})" + ) + + +# For backwards compatibility (equivalent to pre-v1.9): +Retry.DEFAULT = Retry(3) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/ssl_.py b/python/user_packages/Python313/site-packages/urllib3/util/ssl_.py new file mode 100644 index 0000000000000000000000000000000000000000..e66549a76c4b5821e639e5facfeb63dd1a39d543 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/ssl_.py @@ -0,0 +1,477 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import socket +import sys +import typing +import warnings +from binascii import unhexlify + +from ..exceptions import ProxySchemeUnsupported, SSLError +from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE + +SSLContext = None +SSLTransport = None +HAS_NEVER_CHECK_COMMON_NAME = False +IS_PYOPENSSL = False +ALPN_PROTOCOLS = ["http/1.1"] + +_TYPE_VERSION_INFO = tuple[int, int, int, str, int] + +# Maps the length of a digest to a possible hash function producing this digest +HASHFUNC_MAP = { + length: getattr(hashlib, algorithm, None) + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) +} + + +def _is_has_never_check_common_name_reliable( + openssl_version: str, +) -> bool: + # As of May 2023, all released versions of LibreSSL fail to reject certificates with + # only common names, see https://github.com/urllib3/urllib3/pull/3024 + is_openssl = openssl_version.startswith("OpenSSL ") + + return is_openssl + + +if typing.TYPE_CHECKING: + from ssl import VerifyMode + from typing import TypedDict + + from .ssltransport import SSLTransport as SSLTransportType + + class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False): + subjectAltName: tuple[tuple[str, str], ...] + subject: tuple[tuple[tuple[str, str], ...], ...] + serialNumber: str + + +# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X' +_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {} + +try: # Do we have ssl at all? + import ssl + from ssl import ( # type: ignore[assignment] + CERT_REQUIRED, + HAS_NEVER_CHECK_COMMON_NAME, + OP_NO_COMPRESSION, + OP_NO_TICKET, + OPENSSL_VERSION, + PROTOCOL_TLS, + PROTOCOL_TLS_CLIENT, + VERIFY_X509_PARTIAL_CHAIN, + VERIFY_X509_STRICT, + OP_NO_SSLv2, + OP_NO_SSLv3, + SSLContext, + TLSVersion, + ) + + PROTOCOL_SSLv23 = PROTOCOL_TLS + + # Setting SSLContext.hostname_checks_common_name = False didn't work with + # LibreSSL, check details in the used function. + if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable( + OPENSSL_VERSION, + ): # Defensive: + HAS_NEVER_CHECK_COMMON_NAME = False + + # Need to be careful here in case old TLS versions get + # removed in future 'ssl' module implementations. + for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"): + try: + _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr( + TLSVersion, attr + ) + except AttributeError: # Defensive: + continue + + from .ssltransport import SSLTransport # type: ignore[assignment] +except ImportError: + OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment, misc] + OP_NO_TICKET = 0x4000 # type: ignore[assignment, misc] + OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment, misc] + OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment, misc] + PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment, misc] + PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment, misc] + VERIFY_X509_PARTIAL_CHAIN = 0x80000 # type: ignore[assignment,misc] + VERIFY_X509_STRICT = 0x20 # type: ignore[assignment, misc] + + +_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None] + + +def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None: + """ + Checks if given fingerprint matches the supplied certificate. + + :param cert: + Certificate as bytes object. + :param fingerprint: + Fingerprint as string of hexdigits, can be interspersed by colons. + """ + + if cert is None: + raise SSLError("No certificate for the peer.") + + fingerprint = fingerprint.replace(":", "").lower() + digest_length = len(fingerprint) + if digest_length not in HASHFUNC_MAP: + raise SSLError(f"Fingerprint of invalid length: {fingerprint}") + hashfunc = HASHFUNC_MAP.get(digest_length) + if hashfunc is None: + raise SSLError( + f"Hash function implementation unavailable for fingerprint length: {digest_length}" + ) + + # We need encode() here for py32; works on py2 and p33. + fingerprint_bytes = unhexlify(fingerprint.encode()) + + cert_digest = hashfunc(cert).digest() + + if not hmac.compare_digest(cert_digest, fingerprint_bytes): + raise SSLError( + f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"' + ) + + +def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode: + """ + Resolves the argument to a numeric constant, which can be passed to + the wrap_socket function/method from the ssl module. + Defaults to :data:`ssl.CERT_REQUIRED`. + If given a string it is assumed to be the name of the constant in the + :mod:`ssl` module or its abbreviation. + (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. + If it's neither `None` nor a string we assume it is already the numeric + constant which can directly be passed to wrap_socket. + """ + if candidate is None: + return CERT_REQUIRED + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "CERT_" + candidate) + return res # type: ignore[no-any-return] + + return candidate # type: ignore[return-value] + + +def resolve_ssl_version(candidate: None | int | str) -> int: + """ + like resolve_cert_reqs + """ + if candidate is None: + return PROTOCOL_TLS + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "PROTOCOL_" + candidate) + return typing.cast(int, res) + + return candidate + + +def create_urllib3_context( + ssl_version: int | None = None, + cert_reqs: int | None = None, + options: int | None = None, + ciphers: str | None = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + verify_flags: int | None = None, +) -> ssl.SSLContext: + """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3. + + :param ssl_version: + The desired protocol version to use. This will default to + PROTOCOL_SSLv23 which will negotiate the highest protocol that both + the server and your installation of OpenSSL support. + + This parameter is deprecated instead use 'ssl_minimum_version'. + :param ssl_minimum_version: + The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + :param ssl_maximum_version: + The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the + default value. + :param cert_reqs: + Whether to require the certificate verification. This defaults to + ``ssl.CERT_REQUIRED``. + :param options: + Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, + ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. + :param ciphers: + Which cipher suites to allow the server to select. Defaults to either system configured + ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers. + :param verify_flags: + The flags for certificate verification operations. These default to + ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+. + :returns: + Constructed SSLContext object with specified options + :rtype: SSLContext + """ + if SSLContext is None: + raise TypeError("Can't create an SSLContext object without an ssl module") + + # This means 'ssl_version' was specified as an exact value. + if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT): + # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version' + # to avoid conflicts. + if ssl_minimum_version is not None or ssl_maximum_version is not None: + raise ValueError( + "Can't specify both 'ssl_version' and either " + "'ssl_minimum_version' or 'ssl_maximum_version'" + ) + + # 'ssl_version' is deprecated and will be removed in the future. + else: + # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead. + ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MINIMUM_SUPPORTED + ) + ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MAXIMUM_SUPPORTED + ) + + # This warning message is pushing users to use 'ssl_minimum_version' + # instead of both min/max. Best practice is to only set the minimum version and + # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED' + warnings.warn( + "'ssl_version' option is deprecated and will be " + "removed in urllib3 v3.0. Instead use 'ssl_minimum_version'", + category=FutureWarning, + stacklevel=2, + ) + + context = SSLContext(PROTOCOL_TLS_CLIENT) + if ssl_minimum_version is not None: + context.minimum_version = ssl_minimum_version + else: # pyOpenSSL defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here + context.minimum_version = TLSVersion.TLSv1_2 + + if ssl_maximum_version is not None: + context.maximum_version = ssl_maximum_version + + # Unless we're given ciphers defer to either system ciphers in + # the case of OpenSSL 1.1.1+ or use our own secure default ciphers. + if ciphers: + context.set_ciphers(ciphers) + + # Setting the default here, as we may have no ssl module on import + cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if options is None: + options = 0 + # SSLv2 is easily broken and is considered harmful and dangerous + options |= OP_NO_SSLv2 + # SSLv3 has several problems and is now dangerous + options |= OP_NO_SSLv3 + # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ + # (issue #309) + options |= OP_NO_COMPRESSION + # TLSv1.2 only. Unless set explicitly, do not request tickets. + # This may save some bandwidth on wire, and although the ticket is encrypted, + # there is a risk associated with it being on wire, + # if the server is not rotating its ticketing keys properly. + options |= OP_NO_TICKET + + context.options |= options + + if verify_flags is None: + verify_flags = 0 + # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN + # and VERIFY_X509_STRICT so we do the same + if sys.version_info >= (3, 13): + verify_flags |= VERIFY_X509_PARTIAL_CHAIN + verify_flags |= VERIFY_X509_STRICT + + context.verify_flags |= verify_flags + + # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is + # necessary for conditional client cert authentication with TLS 1.3. + # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using + # an SSLContext created by pyOpenSSL. + if getattr(context, "post_handshake_auth", None) is not None: + context.post_handshake_auth = True + + # The order of the below lines setting verify_mode and check_hostname + # matter due to safe-guards SSLContext has to prevent an SSLContext with + # check_hostname=True, verify_mode=NONE/OPTIONAL. + # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own + # 'ssl.match_hostname()' implementation. + if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL: + context.verify_mode = cert_reqs + context.check_hostname = True + else: + context.check_hostname = False + context.verify_mode = cert_reqs + + context.hostname_checks_common_name = False + + if "SSLKEYLOGFILE" in os.environ: + sslkeylogfile = os.path.expandvars(os.environ.get("SSLKEYLOGFILE")) + else: + sslkeylogfile = None + if sslkeylogfile: + context.keylog_filename = sslkeylogfile + + return context + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: typing.Literal[False] = ..., +) -> ssl.SSLSocket: ... + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: bool = ..., +) -> ssl.SSLSocket | SSLTransportType: ... + + +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = None, + certfile: str | None = None, + cert_reqs: int | None = None, + ca_certs: str | None = None, + server_hostname: str | None = None, + ssl_version: int | None = None, + ciphers: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_cert_dir: str | None = None, + key_password: str | None = None, + ca_cert_data: None | str | bytes = None, + tls_in_tls: bool = False, +) -> ssl.SSLSocket | SSLTransportType: + """ + All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and + ca_cert_dir have the same meaning as they do when using + :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`, + :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`. + + :param server_hostname: + When SNI is supported, the expected hostname of the certificate + :param ssl_context: + A pre-made :class:`SSLContext` object. If none is provided, one will + be created using :func:`create_urllib3_context`. + :param ciphers: + A string of ciphers we wish the client to support. + :param ca_cert_dir: + A directory containing CA certificates in multiple separate files, as + supported by OpenSSL's -CApath flag or the capath argument to + SSLContext.load_verify_locations(). + :param key_password: + Optional password if the keyfile is encrypted. + :param ca_cert_data: + Optional string containing CA certificates in PEM format suitable for + passing as the cadata parameter to SSLContext.load_verify_locations() + :param tls_in_tls: + Use SSLTransport to wrap the existing socket. + """ + context = ssl_context + if context is None: + # Note: This branch of code and all the variables in it are only used in tests. + # We should consider deprecating and removing this code. + context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) + + if ca_certs or ca_cert_dir or ca_cert_data: + try: + context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) + except OSError as e: + raise SSLError(e) from e + + elif ssl_context is None and hasattr(context, "load_default_certs"): + # try to load OS default certs; works well on Windows. + context.load_default_certs() + + # Attempt to detect if we get the goofy behavior of the + # keyfile being encrypted and OpenSSL asking for the + # passphrase via the terminal and instead error out. + if keyfile and key_password is None and _is_key_file_encrypted(keyfile): + raise SSLError("Client private key is encrypted, password is required") + + if certfile: + if key_password is None: + context.load_cert_chain(certfile, keyfile) + else: + context.load_cert_chain(certfile, keyfile, key_password) + + context.set_alpn_protocols(ALPN_PROTOCOLS) + + ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname) + return ssl_sock + + +def is_ipaddress(hostname: str | bytes) -> bool: + """Detects whether the hostname given is an IPv4 or IPv6 address. + Also detects IPv6 addresses with Zone IDs. + + :param str hostname: Hostname to examine. + :return: True if the hostname is an IP address, False otherwise. + """ + if isinstance(hostname, bytes): + # IDN A-label bytes are ASCII compatible. + hostname = hostname.decode("ascii") + return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname)) + + +def _is_key_file_encrypted(key_file: str) -> bool: + """Detects if a key file is encrypted or not.""" + with open(key_file) as f: + for line in f: + # Look for Proc-Type: 4,ENCRYPTED + if "ENCRYPTED" in line: + return True + + return False + + +def _ssl_wrap_socket_impl( + sock: socket.socket, + ssl_context: ssl.SSLContext, + tls_in_tls: bool, + server_hostname: str | None = None, +) -> ssl.SSLSocket | SSLTransportType: + if tls_in_tls: + if not SSLTransport: + # Import error, ssl is not available. + raise ProxySchemeUnsupported( + "TLS in TLS requires support for the 'ssl' module" + ) + + SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) + return SSLTransport(sock, ssl_context, server_hostname) + + return ssl_context.wrap_socket(sock, server_hostname=server_hostname) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/ssl_match_hostname.py b/python/user_packages/Python313/site-packages/urllib3/util/ssl_match_hostname.py new file mode 100644 index 0000000000000000000000000000000000000000..94994f25ae1570211c0b98353790f669ef4585fa --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/ssl_match_hostname.py @@ -0,0 +1,153 @@ +"""The match_hostname() function from Python 3.5, essential when using SSL.""" + +# Note: This file is under the PSF license as the code comes from the python +# stdlib. http://docs.python.org/3/license.html +# It is modified to remove commonName support. + +from __future__ import annotations + +import ipaddress +import re +import typing +from ipaddress import IPv4Address, IPv6Address + +if typing.TYPE_CHECKING: + from .ssl_ import _TYPE_PEER_CERT_RET_DICT + +__version__ = "3.5.0.1" + + +class CertificateError(ValueError): + pass + + +def _dnsname_match( + dn: typing.Any, hostname: str, max_wildcards: int = 1 +) -> typing.Match[str] | None | bool: + """Matching according to RFC 6125, section 6.4.3 + + http://tools.ietf.org/html/rfc6125#section-6.4.3 + """ + pats = [] + if not dn: + return False + + # Ported from python3-syntax: + # leftmost, *remainder = dn.split(r'.') + parts = dn.split(r".") + leftmost = parts[0] + remainder = parts[1:] + + wildcards = leftmost.count("*") + if wildcards > max_wildcards: + # Issue #17980: avoid denials of service by refusing more + # than one wildcard per fragment. A survey of established + # policy among SSL implementations showed it to be a + # reasonable choice. + raise CertificateError( + "too many wildcards in certificate DNS name: " + repr(dn) + ) + + # speed up common case w/o wildcards + if not wildcards: + return bool(dn.lower() == hostname.lower()) + + # RFC 6125, section 6.4.3, subitem 1. + # The client SHOULD NOT attempt to match a presented identifier in which + # the wildcard character comprises a label other than the left-most label. + if leftmost == "*": + # When '*' is a fragment by itself, it matches a non-empty dotless + # fragment. + pats.append("[^.]+") + elif leftmost.startswith("xn--") or hostname.startswith("xn--"): + # RFC 6125, section 6.4.3, subitem 3. + # The client SHOULD NOT attempt to match a presented identifier + # where the wildcard character is embedded within an A-label or + # U-label of an internationalized domain name. + pats.append(re.escape(leftmost)) + else: + # Otherwise, '*' matches any dotless string, e.g. www* + pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) + + # add the remaining fragments, ignore any wildcards + for frag in remainder: + pats.append(re.escape(frag)) + + pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) + return pat.match(hostname) + + +def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: + """Exact matching of IP addresses. + + RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded + bytes of the IP address. An IP version 4 address is 4 octets, and an IP + version 6 address is 16 octets. [...] A reference identity of type IP-ID + matches if the address is identical to an iPAddress value of the + subjectAltName extension of the certificate." + """ + # OpenSSL may add a trailing newline to a subjectAltName's IP address + # Divergence from upstream: ipaddress can't handle byte str + ip = ipaddress.ip_address(ipname.rstrip()) + return bool(ip.packed == host_ip.packed) + + +def match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + """Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed, but IP addresses are not accepted for *hostname*. + + CertificateError is raised on failure. On success, the function + returns nothing. + """ + if not cert: + raise ValueError( + "empty or no certificate, match_hostname needs a " + "SSL socket or SSL context with either " + "CERT_OPTIONAL or CERT_REQUIRED" + ) + + try: + host_ip = ipaddress.ip_address(hostname) + except ValueError: + # Not an IP address (common case) + host_ip = None + dnsnames = [] + san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) + key: str + value: str + for key, value in san: + if key == "DNS": + if host_ip is None and _dnsname_match(value, hostname): + return + dnsnames.append(value) + elif key == "IP Address": + if host_ip is not None and _ipaddress_match(value, host_ip): + return + dnsnames.append(value) + + # We only check 'commonName' if it's enabled and we're not verifying + # an IP address. IP addresses aren't valid within 'commonName'. + if hostname_checks_common_name and host_ip is None and not dnsnames: + for sub in cert.get("subject", ()): + for key, value in sub: + if key == "commonName": + if _dnsname_match(value, hostname): + return + dnsnames.append( + value + ) # Defensive: for older PyPy and OpenSSL versions + + if len(dnsnames) > 1: + raise CertificateError( + "hostname %r " + "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) + ) + elif len(dnsnames) == 1: + raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") + else: + raise CertificateError("no appropriate subjectAltName fields were found") diff --git a/python/user_packages/Python313/site-packages/urllib3/util/ssltransport.py b/python/user_packages/Python313/site-packages/urllib3/util/ssltransport.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59bc3bce2489c3a0aa5bcb83b737dcf33c033b --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/ssltransport.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import io +import socket +import ssl +import typing + +from ..exceptions import ProxySchemeUnsupported + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT + + +_WriteBuffer = typing.Union[bytearray, memoryview] +_ReturnValue = typing.TypeVar("_ReturnValue") + +SSL_BLOCKSIZE = 16384 + + +class SSLTransport: + """ + The SSLTransport wraps an existing socket and establishes an SSL connection. + + Contrary to Python's implementation of SSLSocket, it allows you to chain + multiple TLS connections together. It's particularly useful if you need to + implement TLS within TLS. + + The class supports most of the socket API operations. + """ + + @staticmethod + def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None: + """ + Raises a ProxySchemeUnsupported if the provided ssl_context can't be used + for TLS in TLS. + + The only requirement is that the ssl_context provides the 'wrap_bio' + methods. + """ + + if not hasattr(ssl_context, "wrap_bio"): + raise ProxySchemeUnsupported( + "TLS in TLS requires SSLContext.wrap_bio() which isn't " + "available on non-native SSLContext" + ) + + def __init__( + self, + socket: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + suppress_ragged_eofs: bool = True, + ) -> None: + """ + Create an SSLTransport around socket using the provided ssl_context. + """ + self.incoming = ssl.MemoryBIO() + self.outgoing = ssl.MemoryBIO() + + self.suppress_ragged_eofs = suppress_ragged_eofs + self.socket = socket + + self.sslobj = ssl_context.wrap_bio( + self.incoming, self.outgoing, server_hostname=server_hostname + ) + + # Perform initial handshake. + self._ssl_io_loop(self.sslobj.do_handshake) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: typing.Any) -> None: + self.close() + + def fileno(self) -> int: + return self.socket.fileno() + + def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes: + return self._wrap_ssl_read(len, buffer) + + def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv") + return self._wrap_ssl_read(buflen) + + def recv_into( + self, + buffer: _WriteBuffer, + nbytes: int | None = None, + flags: int = 0, + ) -> None | int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into") + if nbytes is None: + nbytes = len(buffer) + return self.read(nbytes, buffer) + + def sendall(self, data: bytes, flags: int = 0) -> None: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to sendall") + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + v = self.send(byte_view[count:]) + count += v + + def send(self, data: bytes, flags: int = 0) -> int: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to send") + return self._ssl_io_loop(self.sslobj.write, data) + + def makefile( + self, + mode: str, + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO: + """ + Python's httpclient uses makefile and buffered io when reading HTTP + messages and we need to support it. + + This is unfortunately a copy and paste of socket.py makefile with small + changes to point to the socket directly. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)") + + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type] + self.socket._io_refs += 1 # type: ignore[attr-defined] + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + buffer: typing.BinaryIO + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment] + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode # type: ignore[misc] + return text + + def unwrap(self) -> None: + self._ssl_io_loop(self.sslobj.unwrap) + + def close(self) -> None: + self.socket.close() + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = ... + ) -> _TYPE_PEER_CERT_RET_DICT | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET: + return self.sslobj.getpeercert(binary_form) # type: ignore[return-value] + + def version(self) -> str | None: + return self.sslobj.version() + + def cipher(self) -> tuple[str, str, int] | None: + return self.sslobj.cipher() + + def selected_alpn_protocol(self) -> str | None: + return self.sslobj.selected_alpn_protocol() + + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: + return self.sslobj.shared_ciphers() + + def compression(self) -> str | None: + return self.sslobj.compression() + + def settimeout(self, value: float | None) -> None: + self.socket.settimeout(value) + + def gettimeout(self) -> float | None: + return self.socket.gettimeout() + + def _decref_socketios(self) -> None: + self.socket._decref_socketios() # type: ignore[attr-defined] + + def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes: + try: + return self._ssl_io_loop(self.sslobj.read, len, buffer) + except ssl.SSLError as e: + if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: + return 0 # eof, return 0. + else: + raise + + # func is sslobj.do_handshake or sslobj.unwrap + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ... + + # func is sslobj.write, arg1 is data + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ... + + # func is sslobj.read, arg1 is len, arg2 is buffer + @typing.overload + def _ssl_io_loop( + self, + func: typing.Callable[[int, bytearray | None], bytes], + arg1: int, + arg2: bytearray | None, + ) -> bytes: ... + + def _ssl_io_loop( + self, + func: typing.Callable[..., _ReturnValue], + arg1: None | bytes | int = None, + arg2: bytearray | None = None, + ) -> _ReturnValue: + """Performs an I/O loop between incoming/outgoing and the socket.""" + should_loop = True + ret = None + + while should_loop: + errno = None + try: + if arg1 is None and arg2 is None: + ret = func() + elif arg2 is None: + ret = func(arg1) + else: + ret = func(arg1, arg2) + except ssl.SSLError as e: + if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + # WANT_READ, and WANT_WRITE are expected, others are not. + raise e + errno = e.errno + + buf = self.outgoing.read() + self.socket.sendall(buf) + + if errno is None: + should_loop = False + elif errno == ssl.SSL_ERROR_WANT_READ: + buf = self.socket.recv(SSL_BLOCKSIZE) + if buf: + self.incoming.write(buf) + else: + self.incoming.write_eof() + return typing.cast(_ReturnValue, ret) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/timeout.py b/python/user_packages/Python313/site-packages/urllib3/util/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb1be11d9cb06900dd82ecebd06aa6a7c5de916 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/timeout.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import time +import typing +from enum import Enum +from socket import getdefaulttimeout + +from ..exceptions import TimeoutStateError + +if typing.TYPE_CHECKING: + from typing import Final + + +class _TYPE_DEFAULT(Enum): + # This value should never be passed to socket.settimeout() so for safety we use a -1. + # socket.settimout() raises a ValueError for negative values. + token = -1 + + +_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token + +_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]] + + +class Timeout: + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + import urllib3 + + timeout = urllib3.util.Timeout(connect=2.0, read=7.0) + + http = urllib3.PoolManager(timeout=timeout) + + resp = http.request("GET", "https://example.com/") + + print(resp.status) + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request("GET", "https://example.com/", timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT + + def __init__( + self, + total: _TYPE_TIMEOUT = None, + connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + ) -> None: + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect: float | None = None + + def __repr__(self) -> str: + return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})" + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @staticmethod + def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None: + return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT: + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is None or value is _DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + return value + + @classmethod + def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout: + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self) -> Timeout: + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self) -> float: + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = time.monotonic() + return self._start_connect + + def get_connect_duration(self) -> float: + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return time.monotonic() - self._start_connect + + @property + def connect_timeout(self) -> _TYPE_TIMEOUT: + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is _DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) # type: ignore[type-var] + + @property + def read_timeout(self) -> float | None: + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not _DEFAULT_TIMEOUT + and self._read is not None + and self._read is not _DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not _DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self.resolve_default_timeout(self._read) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/url.py b/python/user_packages/Python313/site-packages/urllib3/util/url.py new file mode 100644 index 0000000000000000000000000000000000000000..db057f17be610174f30928748b5004dcbf6c501c --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/url.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import re +import typing + +from ..exceptions import LocationParseError +from .util import to_str + +# We only want to normalize urls with an HTTP(S) scheme. +# urllib3 infers URLs without a scheme (None) to be http. +_NORMALIZABLE_SCHEMES = ("http", "https", None) + +# Almost all of these patterns were derived from the +# 'rfc3986' module: https://github.com/python-hyper/rfc3986 +_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") +_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") +_URI_RE = re.compile( + r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" + r"(?://([^\\/?#]*))?" + r"([^?#]*)" + r"(?:\?([^#]*))?" + r"(?:#(.*))?$", + re.UNICODE | re.DOTALL, +) + +_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" +_HEX_PAT = "[0-9A-Fa-f]{1,4}" +_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT) +_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT} +_variations = [ + # 6( h16 ":" ) ls32 + "(?:%(hex)s:){6}%(ls32)s", + # "::" 5( h16 ":" ) ls32 + "::(?:%(hex)s:){5}%(ls32)s", + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", + # [ *4( h16 ":" ) h16 ] "::" ls32 + "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", + # [ *5( h16 ":" ) h16 ] "::" h16 + "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", + # [ *6( h16 ":" ) h16 ] "::" + "(?:(?:%(hex)s:){0,6}%(hex)s)?::", +] + +_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~" +_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" +_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" +_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]" +_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" +_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") + +_IPV4_RE = re.compile("^" + _IPV4_PAT + "$") +_IPV6_RE = re.compile("^" + _IPV6_PAT + "$") +_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$") +_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$") +_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$") + +_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % ( + _REG_NAME_PAT, + _IPV4_PAT, + _IPV6_ADDRZ_PAT, +) +_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) + +_UNRESERVED_CHARS = set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" +) +_SUB_DELIM_CHARS = set("!$&'()*+,;=") +_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"} +_PATH_CHARS = _USERINFO_CHARS | {"@", "/"} +_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"} + + +class Url( + typing.NamedTuple( + "Url", + [ + ("scheme", typing.Optional[str]), + ("auth", typing.Optional[str]), + ("host", typing.Optional[str]), + ("port", typing.Optional[int]), + ("path", typing.Optional[str]), + ("query", typing.Optional[str]), + ("fragment", typing.Optional[str]), + ], + ) +): + """ + Data structure for representing an HTTP URL. Used as a return value for + :func:`parse_url`. Both the scheme and host are normalized as they are + both case-insensitive according to RFC 3986. + """ + + def __new__( # type: ignore[no-untyped-def] + cls, + scheme: str | None = None, + auth: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme is not None: + scheme = scheme.lower() + return super().__new__(cls, scheme, auth, host, port, path, query, fragment) + + @property + def hostname(self) -> str | None: + """For backwards-compatibility with urlparse. We're nice like that.""" + return self.host + + @property + def request_uri(self) -> str: + """Absolute path including the query string.""" + uri = self.path or "/" + + if self.query is not None: + uri += "?" + self.query + + return uri + + @property + def authority(self) -> str | None: + """ + Authority component as defined in RFC 3986 3.2. + This includes userinfo (auth), host and port. + + i.e. + userinfo@host:port + """ + userinfo = self.auth + netloc = self.netloc + if netloc is None or userinfo is None: + return netloc + else: + return f"{userinfo}@{netloc}" + + @property + def netloc(self) -> str | None: + """ + Network location including host and port. + + If you need the equivalent of urllib.parse's ``netloc``, + use the ``authority`` property instead. + """ + if self.host is None: + return None + if self.port: + return f"{self.host}:{self.port}" + return self.host + + @property + def url(self) -> str: + """ + Convert self into a url + + This function should more or less round-trip with :func:`.parse_url`. The + returned url may not be exactly the same as the url inputted to + :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls + with a blank port will have : removed). + + Example: + + .. code-block:: python + + import urllib3 + + U = urllib3.util.parse_url("https://google.com/mail/") + + print(U.url) + # "https://google.com/mail/" + + print( urllib3.util.Url("https", "username:password", + "host.com", 80, "/path", "query", "fragment" + ).url + ) + # "https://username:password@host.com:80/path?query#fragment" + """ + scheme, auth, host, port, path, query, fragment = self + url = "" + + # We use "is not None" we want things to happen with empty strings (or 0 port) + if scheme is not None: + url += scheme + "://" + if auth is not None: + url += auth + "@" + if host is not None: + url += host + if port is not None: + url += ":" + str(port) + if path is not None: + url += path + if query is not None: + url += "?" + query + if fragment is not None: + url += "#" + fragment + + return url + + def __str__(self) -> str: + return self.url + + +@typing.overload +def _encode_invalid_chars( + component: str, allowed_chars: typing.Container[str] +) -> str: # Abstract + ... + + +@typing.overload +def _encode_invalid_chars( + component: None, allowed_chars: typing.Container[str] +) -> None: # Abstract + ... + + +def _encode_invalid_chars( + component: str | None, allowed_chars: typing.Container[str] +) -> str | None: + """Percent-encodes a URI component without reapplying + onto an already percent-encoded component. + """ + if component is None: + return component + + component = to_str(component) + + # Normalize existing percent-encoded bytes. + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + component, percent_encodings = _PERCENT_RE.subn( + lambda match: match.group(0).upper(), component + ) + + uri_bytes = component.encode("utf-8", "surrogatepass") + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + encoded_component = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring + byte = uri_bytes[i : i + 1] + byte_ord = ord(byte) + if (is_percent_encoded and byte == b"%") or ( + byte_ord < 128 and byte.decode() in allowed_chars + ): + encoded_component += byte + continue + encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) + + return encoded_component.decode() + + +def _remove_path_dot_segments(path: str) -> str: + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = path.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + if segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if path.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + if host: + if scheme in _NORMALIZABLE_SCHEMES: + is_ipv6 = _IPV6_ADDRZ_RE.match(host) + if is_ipv6: + # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as + # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID + # separator as necessary to return a valid RFC 4007 scoped IP. + match = _ZONE_ID_RE.search(host) + if match: + start, end = match.span(1) + zone_id = host[start:end] + + if zone_id.startswith("%25") and zone_id != "%25": + zone_id = zone_id[3:] + else: + zone_id = zone_id[1:] + zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS) + return f"{host[:start].lower()}%{zone_id}{host[end:]}" + else: + return host.lower() + elif not _IPV4_RE.match(host): + return to_str( + b".".join([_idna_encode(label) for label in host.split(".")]), + "ascii", + ) + return host + + +def _idna_encode(name: str) -> bytes: + if not name.isascii(): + try: + import idna + except ImportError: + raise LocationParseError( + "Unable to parse URL without the 'idna' module" + ) from None + + try: + return idna.encode(name.lower(), strict=True, std3_rules=True) + except idna.IDNAError: + raise LocationParseError( + f"Name '{name}' is not a valid IDNA label" + ) from None + + return name.lower().encode("ascii") + + +def _encode_target(target: str) -> str: + """Percent-encodes a request target so that there are no invalid characters + + Pre-condition for this function is that 'target' must start with '/'. + If that is the case then _TARGET_RE will always produce a match. + """ + match = _TARGET_RE.match(target) + if not match: # Defensive: + raise LocationParseError(f"{target!r} is not a valid request URI") + + path, query = match.groups() + encoded_target = _encode_invalid_chars(path, _PATH_CHARS) + if query is not None: + query = _encode_invalid_chars(query, _QUERY_CHARS) + encoded_target += "?" + query + return encoded_target + + +def parse_url(url: str) -> Url: + """ + Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is + performed to parse incomplete urls. Fields not provided will be None. + This parser is RFC 3986 and RFC 6874 compliant. + + The parser logic and helper functions are based heavily on + work done in the ``rfc3986`` module. + + :param str url: URL to parse into a :class:`.Url` namedtuple. + + Partly backwards-compatible with :mod:`urllib.parse`. + + Example: + + .. code-block:: python + + import urllib3 + + print( urllib3.util.parse_url('http://google.com/mail/')) + # Url(scheme='http', host='google.com', port=None, path='/mail/', ...) + + print( urllib3.util.parse_url('google.com:80')) + # Url(scheme=None, host='google.com', port=80, path=None, ...) + + print( urllib3.util.parse_url('/foo?bar')) + # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) + """ + if not url: + # Empty + return Url() + + source_url = url + if not _SCHEME_RE.search(url): + url = "//" + url + + scheme: str | None + authority: str | None + auth: str | None + host: str | None + port: str | None + port_int: int | None + path: str | None + query: str | None + fragment: str | None + + try: + scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr] + normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES + + if scheme: + scheme = scheme.lower() + + if authority: + auth, _, host_port = authority.rpartition("@") + auth = auth or None + host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr] + if auth and normalize_uri: + auth = _encode_invalid_chars(auth, _USERINFO_CHARS) + if port == "": + port = None + else: + auth, host, port = None, None, None + + if port is not None: + port_int = int(port) + if not (0 <= port_int <= 65535): + raise LocationParseError(url) + else: + port_int = None + + host = _normalize_host(host, scheme) + + if normalize_uri and path: + path = _remove_path_dot_segments(path) + path = _encode_invalid_chars(path, _PATH_CHARS) + if normalize_uri and query: + query = _encode_invalid_chars(query, _QUERY_CHARS) + if normalize_uri and fragment: + fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS) + + except (ValueError, AttributeError) as e: + raise LocationParseError(source_url) from e + + # For the sake of backwards compatibility we put empty + # string values for path if there are any defined values + # beyond the path in the URL. + # TODO: Remove this when we break backwards compatibility. + if not path: + if query is not None or fragment is not None: + path = "" + else: + path = None + + return Url( + scheme=scheme, + auth=auth, + host=host, + port=port_int, + path=path, + query=query, + fragment=fragment, + ) diff --git a/python/user_packages/Python313/site-packages/urllib3/util/util.py b/python/user_packages/Python313/site-packages/urllib3/util/util.py new file mode 100644 index 0000000000000000000000000000000000000000..35c77e4025842f548565334a3c04cba90f9283d6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/util.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import typing +from types import TracebackType + + +def to_bytes( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> bytes: + if isinstance(x, bytes): + return x + elif not isinstance(x, str): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.encode(encoding or "utf-8", errors=errors or "strict") + return x.encode() + + +def to_str( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> str: + if isinstance(x, str): + return x + elif not isinstance(x, bytes): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.decode(encoding or "utf-8", errors=errors or "strict") + return x.decode() + + +def reraise( + tp: type[BaseException] | None, + value: BaseException, + tb: TracebackType | None = None, +) -> typing.NoReturn: + try: + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None # type: ignore[assignment] + tb = None diff --git a/python/user_packages/Python313/site-packages/urllib3/util/wait.py b/python/user_packages/Python313/site-packages/urllib3/util/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca0c7ad5b232eeb1ad9c43d315bd1d74eaed9a --- /dev/null +++ b/python/user_packages/Python313/site-packages/urllib3/util/wait.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import select +import socket +from functools import partial + +__all__ = ["wait_for_read", "wait_for_write"] + + +# How should we wait on sockets? +# +# There are two types of APIs you can use for waiting on sockets: the fancy +# modern stateful APIs like epoll/kqueue, and the older stateless APIs like +# select/poll. The stateful APIs are more efficient when you have a lots of +# sockets to keep track of, because you can set them up once and then use them +# lots of times. But we only ever want to wait on a single socket at a time +# and don't want to keep track of state, so the stateless APIs are actually +# more efficient. So we want to use select() or poll(). +# +# Now, how do we choose between select() and poll()? On traditional Unixes, +# select() has a strange calling convention that makes it slow, or fail +# altogether, for high-numbered file descriptors. The point of poll() is to fix +# that, so on Unixes, we prefer poll(). +# +# On Windows, there is no poll() (or at least Python doesn't provide a wrapper +# for it), but that's OK, because on Windows, select() doesn't have this +# strange calling convention; plain select() works fine. +# +# So: on Windows we use select(), and everywhere else we use poll(). We also +# fall back to select() in case poll() is somehow broken or missing. + + +def select_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + rcheck = [] + wcheck = [] + if read: + rcheck.append(sock) + if write: + wcheck.append(sock) + # When doing a non-blocking connect, most systems signal success by + # marking the socket writable. Windows, though, signals success by marked + # it as "exceptional". We paper over the difference by checking the write + # sockets for both conditions. (The stdlib selectors module does the same + # thing.) + fn = partial(select.select, rcheck, wcheck, wcheck) + rready, wready, xready = fn(timeout) + return bool(rready or wready or xready) + + +def poll_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + mask = 0 + if read: + mask |= select.POLLIN + if write: + mask |= select.POLLOUT + poll_obj = select.poll() + poll_obj.register(sock, mask) + + # For some reason, poll() takes timeout in milliseconds + def do_poll(t: float | None) -> list[tuple[int, int]]: + if t is not None: + t *= 1000 + return poll_obj.poll(t) + + return bool(do_poll(timeout)) + + +def _have_working_poll() -> bool: + # Apparently some systems have a select.poll that fails as soon as you try + # to use it, either due to strange configuration or broken monkeypatching + # from libraries like eventlet/greenlet. + try: + poll_obj = select.poll() + poll_obj.poll(0) + except (AttributeError, OSError): + return False + else: + return True + + +def wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + # We delay choosing which implementation to use until the first time we're + # called. We could do it at import time, but then we might make the wrong + # decision if someone goes wild with monkeypatching select.poll after + # we're imported. + global wait_for_socket + if _have_working_poll(): + wait_for_socket = poll_wait_for_socket + elif hasattr(select, "select"): + wait_for_socket = select_wait_for_socket + return wait_for_socket(sock, read, write, timeout) + + +def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for reading to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, read=True, timeout=timeout) + + +def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for writing to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, write=True, timeout=timeout) diff --git a/python/user_packages/Python313/site-packages/urwid-3.0.5.dist-info/licenses/COPYING b/python/user_packages/Python313/site-packages/urwid-3.0.5.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..602bfc94635ddf8f1bf2b00419a85ead645a5b67 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid-3.0.5.dist-info/licenses/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ec76b99a9fd1795c4a932d7eb54e10659ca2a53 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/canvas.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/canvas.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..010f60a22bdd61da1522fbc490a6dd549c6dba60 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/canvas.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/command_map.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/command_map.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c383b9484a10548efce6d2afb3c942b7ab043f67 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/command_map.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/container.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/container.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf301d68b9f1148649b0e738e6ec706490139ef1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/container.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/decoration.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/decoration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26a0ab63625a4be01ecfa32f58499e0194c51beb Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/decoration.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/font.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/font.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18924cf5ce46f1d7a0ba7d76c224f06b98088036 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/font.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/graphics.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/graphics.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dba7ae245d668f94391a1ff6b2301bdc17e6fd5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/graphics.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/numedit.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/numedit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ce64324eebd7c1940fa7ebed1a1426b7b5a7d8a Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/numedit.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/signals.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/signals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a2a16b150feaf2925322f98d056ed7744b89966 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/signals.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/split_repr.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/split_repr.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d5e7f8cf4858406b88b8789bd95abcbb588a4b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/split_repr.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/str_util.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/str_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81d75a6b836f9929515fb6e7916af7ac81a16ed9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/str_util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/text_layout.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/text_layout.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6599d09eb6e9cda6ae62f820acfde3a5c4638824 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/text_layout.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d74c5dee51478bcda1db17c4b56aa710cc105569 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38443b67a82e7b9821deaff2e46a034ef93a4332 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/vterm.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/vterm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ae1fe34942a57c94be253dcff558af34357ffb5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/vterm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/__pycache__/wimp.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/__pycache__/wimp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94d7031398baf1f4d2dc9703cbf21865dbe92807 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/__pycache__/wimp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__init__.py b/python/user_packages/Python313/site-packages/urwid/display/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11d2477d9d7209f59d98f7c77b09c3cc2a6e2ee3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/__init__.py @@ -0,0 +1,102 @@ +"""Package with Display implementations for urwid.""" + +from __future__ import annotations + +import importlib.util +import sys +import typing + +from . import raw +from .common import ( + BLACK, + BROWN, + DARK_BLUE, + DARK_CYAN, + DARK_GRAY, + DARK_GREEN, + DARK_MAGENTA, + DARK_RED, + DEFAULT, + LIGHT_BLUE, + LIGHT_CYAN, + LIGHT_GRAY, + LIGHT_GREEN, + LIGHT_MAGENTA, + LIGHT_RED, + UPDATE_PALETTE_ENTRY, + WHITE, + YELLOW, + AttrSpec, + AttrSpecError, + BaseScreen, + RealTerminal, + ScreenError, +) + +if typing.TYPE_CHECKING: + import types + +__all__ = ( + "BLACK", + "BROWN", + "DARK_BLUE", + "DARK_CYAN", + "DARK_GRAY", + "DARK_GREEN", + "DARK_MAGENTA", + "DARK_RED", + "DEFAULT", + "LIGHT_BLUE", + "LIGHT_CYAN", + "LIGHT_GRAY", + "LIGHT_GREEN", + "LIGHT_MAGENTA", + "LIGHT_RED", + "UPDATE_PALETTE_ENTRY", + "WHITE", + "YELLOW", + "AttrSpec", + "AttrSpecError", + "BaseScreen", + "RealTerminal", + "ScreenError", + # Lazy imported + "html_fragment", + "lcd", + "raw", + "web", +) + +try: + from . import curses + + __all__ += ("curses",) +except ImportError: + pass + + +def lazy_import(name: str, package: str | None = None) -> types.ModuleType: + """Lazy import implementation from Python documentation. + + Useful for cases where no warnings expected for moved modules. + """ + spec = importlib.util.find_spec(name, package) + if not spec: + raise ImportError(f"No module named {name!r}") + if not spec.loader: + raise ImportError(f"Module named {name!r} is invalid") + + loader = importlib.util.LazyLoader(spec.loader) + spec.loader = loader + module = importlib.util.module_from_spec(spec) + if not package: + sys.modules[name] = module + else: + sys.modules[f"{package.rstrip('.')}.{name.lstrip('.')}"] = module + loader.exec_module(module) + return module + + +html_fragment = lazy_import(".html_fragment", __package__) +lcd = lazy_import(".lcd", __package__) +web = lazy_import(".web", __package__) diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b218a7825c3127a3a7943c87aa79d07e60207720 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_posix_raw_display.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_posix_raw_display.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61a6639117f12b0d43030e39f901b3b195849d75 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_posix_raw_display.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_raw_display_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_raw_display_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b398518d11a3ffbd77120b8b90fcbcb0161bf3c Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_raw_display_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..278fbb4ec184f1418e423b92d0716066700515d3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32_raw_display.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32_raw_display.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14b8d1086916175723bee3e5912f56053091ac1d Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/_win32_raw_display.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/common.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a2447c6681c5a747aa62bba09de08ba1604afdc Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/curses.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/curses.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecc73c384a7a8c60c7e9d8a70f9ebc903138841b Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/curses.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/escape.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/escape.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73cec71a4b8f9e5f32dd34364169fd85d10bc307 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/escape.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/html_fragment.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/html_fragment.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82916c09e7140144ed58ecc62166d83b1d8d571c Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/html_fragment.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/lcd.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/lcd.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44b32aa7cdd149dd0fc458990bf82a4766e0a4a3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/lcd.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/raw.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/raw.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..718e105d43eb078e3be0ace789727dd5d881633e Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/raw.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/__pycache__/web.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/web.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bec2430c5a2ae5e5f88a719f4d43179c1d490891 Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/display/__pycache__/web.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/urwid/display/_posix_raw_display.py b/python/user_packages/Python313/site-packages/urwid/display/_posix_raw_display.py new file mode 100644 index 0000000000000000000000000000000000000000..65b5990847acebebe81381e4fc55668e78e887b0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_posix_raw_display.py @@ -0,0 +1,424 @@ +# Urwid raw display module +# Copyright (C) 2004-2009 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Direct terminal UI implementation +""" + +from __future__ import annotations + +import contextlib +import fcntl +import functools +import os +import selectors +import signal +import struct +import sys +import termios +import tty +import typing +from subprocess import PIPE, Popen + +from urwid import signals + +from . import _raw_display_base, escape +from .common import INPUT_DESCRIPTORS_CHANGED + +if typing.TYPE_CHECKING: + import socket + from collections.abc import Callable + from types import FrameType + + from urwid.event_loop import EventLoop + + +class Screen(_raw_display_base.Screen): + def __init__( + self, + input: typing.TextIO = sys.stdin, # noqa: A002 # pylint: disable=redefined-builtin + output: typing.TextIO = sys.stdout, + bracketed_paste_mode=False, + focus_reporting=False, + ) -> None: + """Initialize a screen that directly prints escape codes to an output + terminal. + + bracketed_paste_mode -- enable bracketed paste mode in the host terminal. + If the host terminal supports it, the application will receive `begin paste` + and `end paste` keystrokes when the user pastes text. + focus_reporting -- enable focus reporting in the host terminal. + If the host terminal supports it, the application will receive `focus in` + and `focus out` keystrokes when the application gains and loses focus. + """ + super().__init__(input, output) + self.gpm_mev: Popen | None = None + self.gpm_event_pending: bool = False + self.bracketed_paste_mode = bracketed_paste_mode + self.focus_reporting = focus_reporting + + # These store the previous signal handlers after setting ours + self._prev_sigcont_handler = None + self._prev_sigtstp_handler = None + self._prev_sigwinch_handler = None + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__}(" + f"input={self._term_input_file}, " + f"output={self._term_output_file}, " + f"bracketed_paste_mode={self.bracketed_paste_mode}, " + f"focus_reporting={self.focus_reporting})>" + ) + + def _sigwinch_handler(self, signum: int = 28, frame: FrameType | None = None) -> None: + """ + frame -- will always be None when the GLib event loop is being used. + """ + super()._sigwinch_handler(signum, frame) + + if callable(self._prev_sigwinch_handler): + self._prev_sigwinch_handler(signum, frame) + + def _sigtstp_handler(self, signum: int, frame: FrameType | None = None) -> None: + self.stop() # Restores the previous signal handlers + self._prev_sigcont_handler = self.signal_handler_setter(signal.SIGCONT, self._sigcont_handler) + # Handled by the previous handler. + # If non-default, it may set its own SIGCONT handler which should hopefully call our own. + os.kill(os.getpid(), signal.SIGTSTP) + + def _sigcont_handler(self, signum: int, frame: FrameType | None = None) -> None: + """ + frame -- will always be None when the GLib event loop is being used. + """ + self.signal_restore() + + if callable(self._prev_sigcont_handler): + # May set its own SIGTSTP handler which would be stored and replaced in + # `signal_init()` (via `start()`). + self._prev_sigcont_handler(signum, frame) + + self.start() + self._sigwinch_handler(28, None) + + def signal_init(self) -> None: + """ + Called in the startup of run wrapper to set the SIGWINCH + and SIGTSTP signal handlers. + + Override this function to call from main thread in threaded + applications. + """ + self._prev_sigwinch_handler = self.signal_handler_setter(signal.SIGWINCH, self._sigwinch_handler) + self._prev_sigtstp_handler = self.signal_handler_setter(signal.SIGTSTP, self._sigtstp_handler) + + def signal_restore(self) -> None: + """ + Called in the finally block of run wrapper to restore the + SIGTSTP, SIGCONT and SIGWINCH signal handlers. + + Override this function to call from main thread in threaded + applications. + """ + self.signal_handler_setter(signal.SIGTSTP, self._prev_sigtstp_handler or signal.SIG_DFL) + self.signal_handler_setter(signal.SIGCONT, self._prev_sigcont_handler or signal.SIG_DFL) + self.signal_handler_setter(signal.SIGWINCH, self._prev_sigwinch_handler or signal.SIG_DFL) + + def _mouse_tracking(self, enable: bool) -> None: + super()._mouse_tracking(enable) + if enable: + self._start_gpm_tracking() + else: + self._stop_gpm_tracking() + + def _start_gpm_tracking(self) -> None: + if not os.path.isfile("/usr/bin/mev"): + return + if not os.environ.get("TERM", "").lower().startswith("linux"): + return + + m = Popen( # pylint: disable=consider-using-with + ["/usr/bin/mev", "-e", "158"], + stdin=PIPE, + stdout=PIPE, + close_fds=True, + encoding="ascii", + ) + fcntl.fcntl(m.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) + self.gpm_mev = m + + def _stop_gpm_tracking(self) -> None: + if not self.gpm_mev: + return + os.kill(self.gpm_mev.pid, signal.SIGINT) + os.waitpid(self.gpm_mev.pid, 0) + self.gpm_mev = None + + def _start(self, alternate_buffer: bool = True) -> None: + """ + Initialize the screen and input mode. + + alternate_buffer -- use an alternate screen buffer + """ + if alternate_buffer: + self.write(escape.SWITCH_TO_ALTERNATE_BUFFER) + self._rows_used = None + else: + self._rows_used = 0 + + if self.bracketed_paste_mode: + self.write(escape.ENABLE_BRACKETED_PASTE_MODE) + + if self.focus_reporting: + self.write(escape.ENABLE_FOCUS_REPORTING) + + fd = self._input_fileno() + if fd is not None and os.isatty(fd): + self._old_termios_settings = termios.tcgetattr(fd) + tty.setcbreak(fd) + + self.signal_init() + self._alternate_buffer = alternate_buffer + self._next_timeout = self.max_wait + + if not self._signal_keys_set: + self._old_signal_keys = self.tty_signal_keys(fileno=fd) + + signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) + # restore mouse tracking to previous state + self._mouse_tracking(self._mouse_tracking_enabled) + + return super()._start() + + def _stop(self) -> None: + """ + Restore the screen. + """ + self.clear() + + if self.bracketed_paste_mode: + self.write(escape.DISABLE_BRACKETED_PASTE_MODE) + + if self.focus_reporting: + self.write(escape.DISABLE_FOCUS_REPORTING) + + signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) + + self.signal_restore() + + self._stop_mouse_restore_buffer() + + fd = self._input_fileno() + if fd is not None and os.isatty(fd): + termios.tcsetattr(fd, termios.TCSAFLUSH, self._old_termios_settings) + + if self._old_signal_keys: + self.tty_signal_keys(*self._old_signal_keys, fd) + + super()._stop() + + def get_input_descriptors(self) -> list[socket.socket | typing.IO | int]: + """ + Return a list of integer file descriptors that should be + polled in external event loops to check for user input. + + Use this method if you are implementing your own event loop. + + This method is only called by `hook_event_loop`, so if you override + that, you can safely ignore this. + """ + if not self._started: + return [] + + fd_list = super().get_input_descriptors() + if self.gpm_mev is not None and self.gpm_mev.stdout is not None: + fd_list.append(self.gpm_mev.stdout) + return fd_list + + def unhook_event_loop(self, event_loop: EventLoop) -> None: + """ + Remove any hooks added by hook_event_loop. + """ + for handle in self._current_event_loop_handles: + event_loop.remove_watch_file(handle) + + if self._input_timeout: + event_loop.remove_alarm(self._input_timeout) + self._input_timeout = None + + def hook_event_loop( + self, + event_loop: EventLoop, + callback: Callable[[list[str], list[int]], typing.Any], + ) -> None: + """ + Register the given callback with the event loop, to be called with new + input whenever it's available. The callback should be passed a list of + processed keys and a list of unprocessed keycodes. + + Subclasses may wish to use parse_input to wrap the callback. + """ + if hasattr(self, "get_input_nonblocking"): + wrapper = self._make_legacy_input_wrapper(event_loop, callback) + else: + + @functools.wraps(callback) + def wrapper() -> tuple[list[str], typing.Any] | None: + self.logger.debug('Calling callback for "watch file"') + return self.parse_input(event_loop, callback, self.get_available_raw_input()) + + fds = self.get_input_descriptors() + handles = [event_loop.watch_file(fd if isinstance(fd, int) else fd.fileno(), wrapper) for fd in fds] + self._current_event_loop_handles = handles + + def _get_input_codes(self) -> list[int]: + return super()._get_input_codes() + self._get_gpm_codes() + + def _get_gpm_codes(self) -> list[int]: + codes = [] + try: + while self.gpm_mev is not None and self.gpm_event_pending: + codes.extend(self._encode_gpm_event()) + except OSError as e: + if e.args[0] != 11: + raise + return codes + + def _read_raw_input(self, timeout: int) -> bytearray: + ready = self._wait_for_input_ready(timeout) + if self.gpm_mev is not None and self.gpm_mev.stdout.fileno() in ready: + self.gpm_event_pending = True + fd = self._input_fileno() + chars = bytearray() + + if fd is None or fd not in ready: + return chars + + with selectors.DefaultSelector() as selector: + selector.register(fd, selectors.EVENT_READ) + input_ready = selector.select(0) + while input_ready: + chars.extend(os.read(fd, 1024)) + input_ready = selector.select(0) + + return chars + + def _encode_gpm_event(self) -> list[int]: + self.gpm_event_pending = False + s = self.gpm_mev.stdout.readline() + result = s.split(", ") + if len(result) != 6: + # unexpected output, stop tracking + self._stop_gpm_tracking() + signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) + return [] + ev, x, y, _ign, b, m = s.split(",") + ev = int(ev.split("x")[-1], 16) + x = int(x.split(" ")[-1]) + y = int(y.lstrip().split(" ")[0]) + b = int(b.split(" ")[-1]) + m = int(m.split("x")[-1].rstrip(), 16) + + # convert to xterm-like escape sequence + + last_state = next_state = self.last_bstate + result = [] + + mod = 0 + if m & 1: + mod |= 4 # shift + if m & 10: + mod |= 8 # alt + if m & 4: + mod |= 16 # ctrl + + def append_button(b: int) -> None: + b |= mod + result.extend([27, ord("["), ord("M"), b + 32, x + 32, y + 32]) + + if ev in {20, 36, 52}: # press + if b & 4 and last_state & 1 == 0: + append_button(0) + next_state |= 1 + if b & 2 and last_state & 2 == 0: + append_button(1) + next_state |= 2 + if b & 1 and last_state & 4 == 0: + append_button(2) + next_state |= 4 + elif ev == 146: # drag + if b & 4: + append_button(0 + escape.MOUSE_DRAG_FLAG) + elif b & 2: + append_button(1 + escape.MOUSE_DRAG_FLAG) + elif b & 1: + append_button(2 + escape.MOUSE_DRAG_FLAG) + else: # release + if b & 4 and last_state & 1: + append_button(0 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~1 + if b & 2 and last_state & 2: + append_button(1 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~2 + if b & 1 and last_state & 4: + append_button(2 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~4 + if ev == 40: # double click (release) + if b & 4 and last_state & 1: + append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + if b & 2 and last_state & 2: + append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + if b & 1 and last_state & 4: + append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + elif ev == 52: + if b & 4 and last_state & 1: + append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + if b & 2 and last_state & 2: + append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + if b & 1 and last_state & 4: + append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + + self.last_bstate = next_state + return result + + def get_cols_rows(self) -> tuple[int, int]: + """Return the terminal dimensions (num columns, num rows).""" + y, x = super().get_cols_rows() + with contextlib.suppress(OSError): # Term size could not be determined + if hasattr(self._term_output_file, "fileno"): + buf = fcntl.ioctl(self._term_output_file.fileno(), termios.TIOCGWINSZ, b" " * 8) + y, x, _, _ = struct.unpack("hhhh", buf) + + # Provide some lightweight fallbacks in case the TIOCWINSZ doesn't + # give sane answers + if (x <= 0 or y <= 0) and self.term in {"ansi", "vt100"}: + y, x = 24, 80 + self.maxrow = y + return x, y + + +def _test(): + import doctest + + doctest.testmod() + + +if __name__ == "__main__": + _test() diff --git a/python/user_packages/Python313/site-packages/urwid/display/_raw_display_base.py b/python/user_packages/Python313/site-packages/urwid/display/_raw_display_base.py new file mode 100644 index 0000000000000000000000000000000000000000..77ef361aeb36b8dbc934d07a65ad448045016c4f --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_raw_display_base.py @@ -0,0 +1,922 @@ +# Urwid raw display module +# Copyright (C) 2004-2009 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Direct terminal UI implementation +""" + +from __future__ import annotations + +import abc +import contextlib +import functools +import os +import platform +import selectors +import signal +import socket +import sys +import typing + +from urwid import signals, str_util, util + +from . import escape +from .common import UNPRINTABLE_TRANS_TABLE, UPDATE_PALETTE_ENTRY, AttrSpec, BaseScreen, RealTerminal + +if typing.TYPE_CHECKING: + from collections.abc import Callable, Iterable + from types import FrameType + + from typing_extensions import Literal + + from urwid import Canvas, EventLoop + +IS_WINDOWS = sys.platform == "win32" +IS_WSL = (sys.platform == "linux") and ("wsl" in platform.platform().lower()) + + +class Screen(BaseScreen, RealTerminal): + def __init__(self, input: typing.IO, output: typing.IO) -> None: # noqa: A002 # pylint: disable=redefined-builtin + """Initialize a screen that directly prints escape codes to an output + terminal. + """ + super().__init__() + + self._partial_codes: list[int] = [] + self._pal_escape: dict[str | None, str] = {} + self._pal_attrspec: dict[str | None, AttrSpec] = {} + self._alternate_buffer: bool = False + signals.connect_signal(self, UPDATE_PALETTE_ENTRY, self._on_update_palette_entry) + self.colors: Literal[1, 16, 88, 256, 16777216] = 16 # FIXME: detect this + self.has_underline = True # FIXME: detect this + self.prev_input_resize = 0 + self.set_input_timeouts() + self.screen_buf = None + self._screen_buf_canvas = None + self._resized = False + self.maxrow = None + self._mouse_tracking_enabled = False + self.last_bstate = 0 + self._setup_G1_done = False + self._rows_used = None + self._cy = 0 + self.term = os.environ.get("TERM", "") + self.fg_bright_is_bold = not self.term.startswith("xterm") + self.bg_bright_is_blink = self.term == "linux" + self.back_color_erase = not self.term.startswith("screen") + self.register_palette_entry(None, "default", "default") + self._next_timeout = None + self.signal_handler_setter = signal.signal + + # Our connections to the world + self._term_output_file = output + self._term_input_file = input + + # pipe for signalling external event loops about resize events + self._resize_pipe_rd, self._resize_pipe_wr = socket.socketpair() + self._resize_pipe_rd.setblocking(False) + + def __del__(self) -> None: + self._resize_pipe_rd.close() + self._resize_pipe_wr.close() + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}(input={self._term_input_file}, output={self._term_output_file})>" + + def _sigwinch_handler(self, signum: int = 28, frame: FrameType | None = None) -> None: + """ + frame -- will always be None when the GLib event loop is being used. + """ + logger = self.logger.getChild("signal_handlers") + + logger.debug(f"SIGWINCH handler called with signum={signum!r}, frame={frame!r}") + + if IS_WINDOWS or not self._resized: + self._resize_pipe_wr.send(b"R") + logger.debug("Sent fake resize input to the pipe") + self._resized = True + self.screen_buf = None + + @property + def _term_input_io(self) -> typing.IO | None: + if hasattr(self._term_input_file, "fileno"): + return self._term_input_file + return None + + def _input_fileno(self) -> int | None: + """Returns the fileno of the input stream, or None if it doesn't have one. + + A stream without a fileno can't participate in whatever. + """ + if hasattr(self._term_input_file, "fileno"): + return self._term_input_file.fileno() + + return None + + def _on_update_palette_entry(self, name: str | None, *attrspecs: AttrSpec): + # copy the attribute to a dictionary containing the escape seqences + a: AttrSpec = attrspecs[{16: 0, 1: 1, 88: 2, 256: 3, 2**24: 4}[self.colors]] + self._pal_attrspec[name] = a + self._pal_escape[name] = self._attrspec_to_escape(a) + + def set_input_timeouts( + self, + max_wait: float | None = None, + complete_wait: float = 0.125, + resize_wait: float = 0.125, + ) -> None: + """ + Set the get_input timeout values. All values are in floating + point numbers of seconds. + + max_wait -- amount of time in seconds to wait for input when + there is no input pending, wait forever if None + complete_wait -- amount of time in seconds to wait when + get_input detects an incomplete escape sequence at the + end of the available input + resize_wait -- amount of time in seconds to wait for more input + after receiving two screen resize requests in a row to + stop Urwid from consuming 100% cpu during a gradual + window resize operation + """ + self.max_wait = max_wait + if max_wait is not None: + if self._next_timeout is None: + self._next_timeout = max_wait + else: + self._next_timeout = min(self._next_timeout, self.max_wait) + self.complete_wait = complete_wait + self.resize_wait = resize_wait + + def set_mouse_tracking(self, enable: bool = True) -> None: + """ + Enable (or disable) mouse tracking. + + After calling this function get_input will include mouse + click events along with keystrokes. + """ + enable = bool(enable) + if enable == self._mouse_tracking_enabled: + return + + self._mouse_tracking(enable) + self._mouse_tracking_enabled = enable + + def _mouse_tracking(self, enable: bool) -> None: + if enable: + self.write(escape.MOUSE_TRACKING_ON) + else: + self.write(escape.MOUSE_TRACKING_OFF) + + @abc.abstractmethod + def _start(self, alternate_buffer: bool = True) -> None: + """ + Initialize the screen and input mode. + + alternate_buffer -- use alternate screen buffer + """ + + def _stop_mouse_restore_buffer(self) -> None: + """Stop mouse tracking and restore the screen.""" + self._mouse_tracking(False) + + move_cursor = "" + if self._alternate_buffer: + move_cursor = escape.RESTORE_NORMAL_BUFFER + elif self.maxrow is not None: + move_cursor = escape.set_cursor_position(0, self.maxrow) + self.write(self._attrspec_to_escape(AttrSpec("", "")) + escape.SI + move_cursor + escape.SHOW_CURSOR) + self.flush() + + @abc.abstractmethod + def _stop(self) -> None: + """ + Restore the screen. + """ + + def write(self, data: str) -> None: + """Write some data to the terminal. + + You may wish to override this if you're using something other than + regular files for input and output. + """ + self._term_output_file.write(data) + + def flush(self) -> None: + """Flush the output buffer. + + You may wish to override this if you're using something other than + regular files for input and output. + """ + self._term_output_file.flush() + + @typing.overload + def get_input(self, raw_keys: Literal[False]) -> list[str]: ... + + @typing.overload + def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... + + def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: + """Return pending input as a list. + + raw_keys -- return raw keycodes as well as translated versions + + This function will immediately return all the input since the + last time it was called. If there is no input pending it will + wait before returning an empty list. The wait time may be + configured with the set_input_timeouts function. + + If raw_keys is False (default) this function will return a list + of keys pressed. If raw_keys is True this function will return + a ( keys pressed, raw keycodes ) tuple instead. + + Examples of keys returned: + + * ASCII printable characters: " ", "a", "0", "A", "-", "/" + * ASCII control characters: "tab", "enter" + * Escape sequences: "up", "page up", "home", "insert", "f1" + * Key combinations: "shift f1", "meta a", "ctrl b" + * Window events: "window resize" + + When a narrow encoding is not enabled: + + * "Extended ASCII" characters: "\\xa1", "\\xb2", "\\xfe" + + When a wide encoding is enabled: + + * Double-byte characters: "\\xa1\\xea", "\\xb2\\xd4" + + When utf8 encoding is enabled: + + * Unicode characters: u"\\u00a5", u'\\u253c" + + Examples of mouse events returned: + + * Mouse button press: ('mouse press', 1, 15, 13), + ('meta mouse press', 2, 17, 23) + * Mouse drag: ('mouse drag', 1, 16, 13), + ('mouse drag', 1, 17, 13), + ('ctrl mouse drag', 1, 18, 13) + * Mouse button release: ('mouse release', 0, 18, 13), + ('ctrl mouse release', 0, 17, 23) + """ + logger = self.logger.getChild("get_input") + if not self._started: + raise RuntimeError + + self._wait_for_input_ready(self._next_timeout) + keys, raw = self.parse_input(None, None, self.get_available_raw_input()) + + # Avoid pegging CPU at 100% when slowly resizing + if keys == ["window resize"] and self.prev_input_resize: + logger.debug('get_input: got "window resize" > 1 times. Enable throttling for resize.') + for _ in range(2): + self._wait_for_input_ready(self.resize_wait) + new_keys, new_raw = self.parse_input(None, None, self.get_available_raw_input()) + raw += new_raw + if new_keys and new_keys != ["window resize"]: + if "window resize" in new_keys: + keys = new_keys + else: + keys.extend(new_keys) + break + + if keys == ["window resize"]: + self.prev_input_resize = 2 + elif self.prev_input_resize == 2 and not keys: + self.prev_input_resize = 1 + else: + self.prev_input_resize = 0 + + if raw_keys: + return keys, raw + return keys + + def get_input_descriptors(self) -> list[socket.socket | typing.IO | int]: + """ + Return a list of integer file descriptors that should be + polled in external event loops to check for user input. + + Use this method if you are implementing your own event loop. + + This method is only called by `hook_event_loop`, so if you override + that, you can safely ignore this. + """ + if not self._started: + return [] + + fd_list: list[socket.socket | typing.IO | int] = [self._resize_pipe_rd] + + if (input_io := self._term_input_io) is not None: + fd_list.append(input_io) + return fd_list + + _current_event_loop_handles = () + + @abc.abstractmethod + def unhook_event_loop(self, event_loop: EventLoop) -> None: + """ + Remove any hooks added by hook_event_loop. + """ + + @abc.abstractmethod + def hook_event_loop( + self, + event_loop: EventLoop, + callback: Callable[[list[str], list[int]], typing.Any], + ) -> None: + """ + Register the given callback with the event loop, to be called with new + input whenever it's available. The callback should be passed a list of + processed keys and a list of unprocessed keycodes. + + Subclasses may wish to use parse_input to wrap the callback. + """ + + _input_timeout = None + + def _make_legacy_input_wrapper( + self, + event_loop: EventLoop, + callback: Callable[[list[str], list[int]], typing.Any], + ) -> Callable[[], None]: + """ + Support old Screen classes that still have a get_input_nonblocking and expect it to work. + """ + + @functools.wraps(callback) + def wrapper(): + if self._input_timeout: + event_loop.remove_alarm(self._input_timeout) + self._input_timeout = None + timeout, keys, raw = self.get_input_nonblocking() # pylint: disable=no-member # should we deprecate? + if timeout is not None: + self._input_timeout = event_loop.alarm(timeout, wrapper) + + callback(keys, raw) + + return wrapper + + def _get_input_codes(self) -> list[int]: + return list(self._get_keyboard_codes()) + + def get_available_raw_input(self) -> list[int]: + """ + Return any currently available input. Does not block. + + This method is only used by the default `hook_event_loop` + implementation; you can safely ignore it if you implement your own. + """ + logger = self.logger.getChild("get_available_raw_input") + codes = [*self._partial_codes, *self._get_input_codes()] + self._partial_codes = [] + + # clean out the pipe used to signal external event loops + # that a resize has occurred + with selectors.DefaultSelector() as selector: + selector.register(self._resize_pipe_rd, selectors.EVENT_READ) + present_resize_flag = selector.select(0) # nonblocking + while present_resize_flag: + logger.debug("Resize signal received. Cleaning socket.") + # Argument "size" is maximum buffer size to read. Since we're emptying, set it reasonably big. + self._resize_pipe_rd.recv(128) + present_resize_flag = selector.select(0) + + return codes + + @typing.overload + def parse_input( + self, + event_loop: None, + callback: None, + codes: list[int], + wait_for_more: bool = ..., + ) -> tuple[list[str], list[int]]: ... + + @typing.overload + def parse_input( + self, + event_loop: EventLoop, + callback: None, + codes: list[int], + wait_for_more: bool = ..., + ) -> tuple[list[str], list[int]]: ... + + @typing.overload + def parse_input( + self, + event_loop: EventLoop, + callback: Callable[[list[str], list[int]], typing.Any], + codes: list[int], + wait_for_more: bool = ..., + ) -> None: ... + + def parse_input( + self, + event_loop: EventLoop | None, + callback: Callable[[list[str], list[int]], typing.Any] | None, + codes: list[int], + wait_for_more: bool = True, + ) -> tuple[list[str], list[int]] | None: + """ + Read any available input from get_available_raw_input, parses it into + keys, and calls the given callback. + + The current implementation tries to avoid any assumptions about what + the screen or event loop look like; it only deals with parsing keycodes + and setting a timeout when an incomplete one is detected. + + `codes` should be a sequence of keycodes, i.e. bytes. A bytearray is + appropriate, but beware of using bytes, which only iterates as integers + on Python 3. + """ + + logger = self.logger.getChild("parse_input") + + # Note: event_loop may be None for 100% synchronous support, only used + # by get_input. Not documented because you shouldn't be doing it. + if self._input_timeout and event_loop: + event_loop.remove_alarm(self._input_timeout) + self._input_timeout = None + + original_codes = codes + decoded_codes = [] + try: + while codes: + run, codes = escape.process_keyqueue(codes, wait_for_more) + decoded_codes.extend(run) + except escape.MoreInputRequired: + # Set a timer to wait for the rest of the input; if it goes off + # without any new input having come in, use the partial input + k = len(original_codes) - len(codes) + raw_codes = original_codes[:k] + self._partial_codes = codes + + def _parse_incomplete_input(): + self._input_timeout = None + self._partial_codes = [] + self.parse_input(event_loop, callback, codes, wait_for_more=False) + + if event_loop: + self._input_timeout = event_loop.alarm(self.complete_wait, _parse_incomplete_input) + + else: + raw_codes = original_codes + self._partial_codes = [] + + logger.debug(f"Decoded codes: {decoded_codes!r}, raw codes: {raw_codes!r}") + + if self._resized: + decoded_codes.append("window resize") + logger.debug('Added "window resize" to the codes') + self._resized = False + + if callback: + callback(decoded_codes, raw_codes) + return None + + # For get_input + return decoded_codes, raw_codes + + def _wait_for_input_ready(self, timeout: float | None) -> list[int]: + logger = self.logger.getChild("wait_for_input_ready") + fd_list = self.get_input_descriptors() + + logger.debug(f"Waiting for input: descriptors={fd_list!r}, timeout={timeout!r}") + with selectors.DefaultSelector() as selector: + for fd in fd_list: + selector.register(fd, selectors.EVENT_READ) + + ready = selector.select(timeout) + + logger.debug(f"Input ready: {ready}") + + return [event.fd for event, _ in ready] + + @abc.abstractmethod + def _read_raw_input(self, timeout: int) -> Iterable[int]: ... + + def _get_keyboard_codes(self) -> Iterable[int]: + return self._read_raw_input(0) + + def _setup_G1(self) -> None: + """ + Initialize the G1 character set to graphics mode if required. + """ + if self._setup_G1_done: + return + + while True: + with contextlib.suppress(OSError): + self.write(escape.DESIGNATE_G1_SPECIAL) + self.flush() + break + self._setup_G1_done = True + + def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: + """Paint screen with rendered canvas.""" + + def set_cursor_home() -> str: + if not partial_display(): + return escape.set_cursor_position(0, 0) + return escape.CURSOR_HOME_COL + escape.move_cursor_up(cy) + + def set_cursor_position(x: int, y: int) -> str: + if not partial_display(): + return escape.set_cursor_position(x, y) + if cy > y: + return "\b" + escape.CURSOR_HOME_COL + escape.move_cursor_up(cy - y) + escape.move_cursor_right(x) + return "\b" + escape.CURSOR_HOME_COL + escape.move_cursor_down(y - cy) + escape.move_cursor_right(x) + + def is_blank_row(row: list[tuple[object, Literal["0", "U"] | None], bytes]) -> bool: + if len(row) > 1: + return False + return not row[0][2].strip() + + def attr_to_escape(a: AttrSpec | str | None) -> str: + if a in self._pal_escape: + return self._pal_escape[a] + if isinstance(a, AttrSpec): + return self._attrspec_to_escape(a) + if a is None: + return self._attrspec_to_escape(AttrSpec("default", "default")) + # undefined attributes use default/default + self.logger.debug(f"Undefined attribute: {a!r}") + return self._attrspec_to_escape(AttrSpec("default", "default")) + + def using_standout_or_underline(a: AttrSpec | str) -> bool: + a = self._pal_attrspec.get(a, a) + return isinstance(a, AttrSpec) and (a.standout or a.underline) + + encoding = util.get_encoding() + + logger = self.logger.getChild("draw_screen") + + (maxcol, maxrow) = size + + if not self._started: + raise RuntimeError + + if maxrow != canvas.rows(): + raise ValueError(maxrow) + + # quick return if nothing has changed + if self.screen_buf and canvas is self._screen_buf_canvas: + return + + self._setup_G1() + + if self._resized: + # handle resize before trying to draw screen + logger.debug("Not drawing screen: screen resized and resize was not handled") + return + + logger.debug(f"Drawing screen with size {size!r}") + + last_attributes = None # Default = empty + + output: list[str] = [escape.HIDE_CURSOR, attr_to_escape(last_attributes)] + + def partial_display() -> bool: + # returns True if the screen is in partial display mode ie. only some rows belong to the display + return self._rows_used is not None + + if not partial_display(): + output.append(escape.CURSOR_HOME) + + if self.screen_buf: + osb = self.screen_buf + else: + osb = [] + sb: list[list[tuple[object, Literal["0", "U"] | None, bytes]]] = [] + cy = self._cy + y = -1 + + ins = None + output.append(set_cursor_home()) + cy = 0 + + first = True + last_charset_flag = None + + for row in canvas.content(): + y += 1 + if osb and y < len(osb) and osb[y] == row: + # this row of the screen buffer matches what is + # currently displayed, so we can skip this line + sb.append(osb[y]) + continue + + sb.append(row) + + # leave blank lines off display when we are using + # the default screen buffer (allows partial screen) + if partial_display() and y > self._rows_used: + if is_blank_row(row): + continue + self._rows_used = y + + if y or partial_display(): + output.append(set_cursor_position(0, y)) + # after updating the line we will be just over the + # edge, but terminals still treat this as being + # on the same line + cy = y + + whitespace_at_end = False + if row: + a, cs, run = row[-1] + if run[-1:] == b" " and self.back_color_erase and not using_standout_or_underline(a): + whitespace_at_end = True + row = [*row[:-1], (a, cs, run.rstrip(b" "))] # noqa: PLW2901 + elif y == maxrow - 1 and maxcol > 1: + row, back, ins = self._last_row(row) # noqa: PLW2901 + + for a, cs, run in row: + if not isinstance(run, bytes): # canvases render with bytes + raise TypeError(run) + + if cs != "U": + run = run.translate(UNPRINTABLE_TRANS_TABLE) # noqa: PLW2901 + + if last_attributes != a: + output.append(attr_to_escape(a)) + last_attributes = a + + if encoding != "utf-8" and (first or last_charset_flag != cs): + if cs not in {None, "0", "U"}: + raise ValueError(cs) + if last_charset_flag == "U": + output.append(escape.IBMPC_OFF) + + if cs is None: + output.append(escape.SI) + elif cs == "U": + output.append(escape.IBMPC_ON) + else: + output.append(escape.SO) + last_charset_flag = cs + + output.append(run.decode(encoding, "replace")) + first = False + + if ins: + (inserta, insertcs, inserttext) = ins + ias = attr_to_escape(inserta) + if insertcs not in {None, "0", "U"}: + raise ValueError(insertcs) + + if isinstance(inserttext, bytes): + inserttext = inserttext.decode(encoding) + + output.extend(("\x08" * back, ias)) # pylint: disable=used-before-assignment # defined in `if row` + + if encoding != "utf-8": + if cs is None: + icss = escape.SI + elif cs == "U": + icss = escape.IBMPC_ON + else: + icss = escape.SO + + output.append(icss) + + if not IS_WINDOWS: + output += [escape.INSERT_ON, inserttext, escape.INSERT_OFF] + else: + output += [f"{escape.ESC}[{str_util.calc_width(inserttext, 0, len(inserttext))}@", inserttext] + + if encoding != "utf-8" and cs == "U": + output.append(escape.IBMPC_OFF) + + if whitespace_at_end: + output.append(escape.ERASE_IN_LINE_RIGHT) + + if canvas.cursor is not None: + x, y = canvas.cursor + output += [set_cursor_position(x, y), escape.SHOW_CURSOR] + self._cy = y + + if self._resized: + # handle resize before trying to draw screen + return + try: + for line in output: + if isinstance(line, bytes): + line = line.decode(encoding, "replace") # noqa: PLW2901 + self.write(line) + self.flush() + except OSError as e: + # ignore interrupted syscall + if e.args[0] != 4: + raise + + self.screen_buf = sb + self._screen_buf_canvas = canvas + + def _last_row( + self, + row: list[tuple[object, Literal["0", "U"] | None, bytes]], + ) -> tuple[ + list[tuple[object, Literal["0", "U"] | None, bytes]], + int, + tuple[object, Literal["0", "U"] | None, bytes], + ]: + """On the last row we need to slide the bottom right character + into place. Calculate the new line, attr and an insert sequence + to do that. + + eg. last row: + XXXXXXXXXXXXXXXXXXXXYZ + + Y will be drawn after Z, shifting Z into position. + """ + + new_row = row[:-1] + z_attr, z_cs, last_text = row[-1] + last_cols = str_util.calc_width(last_text, 0, len(last_text)) + last_offs, z_col = str_util.calc_text_pos(last_text, 0, len(last_text), last_cols - 1) + if last_offs == 0: + z_text = last_text + del new_row[-1] + # we need another segment + y_attr, y_cs, nlast_text = row[-2] + nlast_cols = str_util.calc_width(nlast_text, 0, len(nlast_text)) + z_col += nlast_cols + nlast_offs, y_col = str_util.calc_text_pos(nlast_text, 0, len(nlast_text), nlast_cols - 1) + y_text = nlast_text[nlast_offs:] + if nlast_offs: + new_row.append((y_attr, y_cs, nlast_text[:nlast_offs])) + else: + z_text = last_text[last_offs:] + y_attr, y_cs = z_attr, z_cs + nlast_cols = str_util.calc_width(last_text, 0, last_offs) + nlast_offs, y_col = str_util.calc_text_pos(last_text, 0, last_offs, nlast_cols - 1) + y_text = last_text[nlast_offs:last_offs] + if nlast_offs: + new_row.append((y_attr, y_cs, last_text[:nlast_offs])) + + new_row.append((z_attr, z_cs, z_text)) + return new_row, z_col - y_col, (y_attr, y_cs, y_text) + + def clear(self) -> None: + """ + Force the screen to be completely repainted on the next + call to draw_screen(). + """ + self.screen_buf = None + + def _attrspec_to_escape(self, a: AttrSpec) -> str: + """ + Convert AttrSpec instance a to an escape sequence for the terminal + + >>> s = Screen() + >>> s.set_terminal_properties(colors=256) + >>> a2e = s._attrspec_to_escape + >>> a2e(s.AttrSpec("brown", "dark green")) + '\\x1b[0;33;42m' + >>> a2e(s.AttrSpec("#fea,underline", "#d0d")) + '\\x1b[0;38;5;229;4;48;5;164m' + """ + if self.term == "fbterm": + fg = escape.ESC + f"[1;{a.foreground_number:d}}}" + bg = escape.ESC + f"[2;{a.background_number:d}}}" + return fg + bg + + if a.foreground_true: + fg = f"38;2;{';'.join(str(part) for part in a.get_rgb_values()[0:3])}" + elif a.foreground_high: + fg = f"38;5;{a.foreground_number:d}" + elif a.foreground_basic: + if a.foreground_number > 7: + if self.fg_bright_is_bold: + fg = f"1;{a.foreground_number - 8 + 30:d}" + else: + fg = f"{a.foreground_number - 8 + 90:d}" + else: + fg = f"{a.foreground_number + 30:d}" + else: + fg = "39" + st = ( + "1;" * a.bold + + "3;" * a.italics + + "4;" * a.underline + + "5;" * a.blink + + "7;" * a.standout + + "9;" * a.strikethrough + ) + if a.background_true: + bg = f"48;2;{';'.join(str(part) for part in a.get_rgb_values()[3:6])}" + elif a.background_high: + bg = f"48;5;{a.background_number:d}" + elif a.background_basic: + if a.background_number > 7: + if self.bg_bright_is_blink: + bg = f"5;{a.background_number - 8 + 40:d}" + else: + # this doesn't work on most terminals + bg = f"{a.background_number - 8 + 100:d}" + else: + bg = f"{a.background_number + 40:d}" + else: + bg = "49" + return f"{escape.ESC}[0;{fg};{st}{bg}m" + + def set_terminal_properties( + self, + colors: Literal[1, 16, 88, 256, 16777216] | None = None, + bright_is_bold: bool | None = None, + has_underline: bool | None = None, + ) -> None: + """ + colors -- number of colors terminal supports (1, 16, 88, 256, or 2**24) + or None to leave unchanged + bright_is_bold -- set to True if this terminal uses the bold + setting to create bright colors (numbers 8-15), set to False + if this Terminal can create bright colors without bold or + None to leave unchanged + has_underline -- set to True if this terminal can use the + underline setting, False if it cannot or None to leave + unchanged + """ + if colors is None: + colors = self.colors + if bright_is_bold is None: + bright_is_bold = self.fg_bright_is_bold + if has_underline is None: + has_underline = self.has_underline + + if colors == self.colors and bright_is_bold == self.fg_bright_is_bold and has_underline == self.has_underline: + return + + self.colors = colors + self.fg_bright_is_bold = bright_is_bold + self.has_underline = has_underline + + self.clear() + self._pal_escape = {} + for p, v in self._palette.items(): + self._on_update_palette_entry(p, *v) + + def reset_default_terminal_palette(self) -> None: + """ + Attempt to set the terminal palette to default values as taken from xterm. + Uses a number of colors from the current set_terminal_properties() screen setting. + """ + if self.colors == 1: + return + if self.colors == 2**24: + colors = 256 + else: + colors = self.colors + + def rgb_values(n) -> tuple[int | None, int | None, int | None]: + if colors == 16: + aspec = AttrSpec(f"h{n:d}", "", 256) + else: + aspec = AttrSpec(f"h{n:d}", "", colors) + return aspec.get_rgb_values()[:3] + + entries = [(n, *rgb_values(n)) for n in range(min(colors, 256))] + self.modify_terminal_palette(entries) + + def modify_terminal_palette(self, entries: list[tuple[int, int | None, int | None, int | None]]): + """ + entries - list of (index, red, green, blue) tuples. + + Attempt to set part of the terminal palette (this does not work on all terminals.) + The changes are sent as a single escape sequence so they should all take effect at the same time. + + 0 <= index < 256 (some terminals will only have 16 or 88 colors) + 0 <= red, green, blue < 256 + """ + + if self.term == "fbterm": + modify = [f"{index:d};{red:d};{green:d};{blue:d}" for index, red, green, blue in entries] + self.write(f"\x1b[3;{';'.join(modify)}}}") + else: + modify = [f"{index:d};rgb:{red:02x}/{green:02x}/{blue:02x}" for index, red, green, blue in entries] + self.write(f"\x1b]4;{';'.join(modify)}\x1b\\") + self.flush() + + # shortcut for creating an AttrSpec with this screen object's + # number of colors + def AttrSpec(self, fg, bg) -> AttrSpec: + return AttrSpec(fg, bg, self.colors) diff --git a/python/user_packages/Python313/site-packages/urwid/display/_web.css b/python/user_packages/Python313/site-packages/urwid/display/_web.css new file mode 100644 index 0000000000000000000000000000000000000000..18525f99625ec8d2926c5229583a9c83dca2d222 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_web.css @@ -0,0 +1,12 @@ +body { margin: 8px 8px 8px 8px; border: 0; + color: black; background-color: silver; + font-family: fixed; overflow: hidden; } + +form { margin: 0 0 8px 0; } + +#text { position: relative; + background-color: silver; + width: 100%; height: 100%; + margin: 3px 0 0 0; border: 1px solid #999; } + +#page { position: relative; width: 100%;height: 100%;} diff --git a/python/user_packages/Python313/site-packages/urwid/display/_web.js b/python/user_packages/Python313/site-packages/urwid/display/_web.js new file mode 100644 index 0000000000000000000000000000000000000000..17678af0dc2b30b5f0e3023703afc04681366f4a --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_web.js @@ -0,0 +1,462 @@ +// Urwid web (CGI/Asynchronous Javascript) display module +// Copyright (C) 2004-2005 Ian Ward +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Urwid web site: https://urwid.org/ + +colours = new Object(); +colours = { + '0': "black", + '1': "#c00000", + '2': "green", + '3': "#804000", + '4': "#0000c0", + '5': "#c000c0", + '6': "teal", + '7': "silver", + '8': "gray", + '9': "#ff6060", + 'A': "lime", + 'B': "yellow", + 'C': "#8080ff", + 'D': "#ff40ff", + 'E': "aqua", + 'F': "white" +}; + +keycodes = new Object(); +keycodes = { + 8: "backspace", 9: "tab", 13: "enter", 27: "esc", + 33: "page up", 34: "page down", 35: "end", 36: "home", + 37: "left", 38: "up", 39: "right", 40: "down", + 45: "insert", 46: "delete", + 112: "f1", 113: "f2", 114: "f3", 115: "f4", + 116: "f5", 117: "f6", 118: "f7", 119: "f8", + 120: "f9", 121: "f10", 122: "f11", 123: "f12" + }; + +var conn = null; +var char_width = null; +var char_height = null; +var screen_x = null; +var screen_y = null; + +var urwid_id = null; +var send_conn = null; +var send_queue_max = 32; +var send_queue = new Array(send_queue_max); +var send_queue_in = 0; +var send_queue_out = 0; + +var check_font_delay = 1000; +var send_more_delay = 100; +var poll_again_delay = 500; + +var document_location = null; + +var update_method = "multipart"; + +var sending = false; +var lastkeydown = null; + +function setup_connection() { + if (window.XMLHttpRequest) { + conn = new XMLHttpRequest(); + } else if (window.ActiveXObject) { + conn = new ActiveXObject("Microsoft.XMLHTTP"); + } + + if (conn == null) { + set_status("Connection Failed"); + alert( "Can't figure out how to send request." ); + return; + } + try{ + conn.multipart = true; + }catch(e){ + update_method = "polling"; + } + conn.onreadystatechange = handle_recv; + conn.open("POST", document_location, true); + conn.setRequestHeader("X-Urwid-Method",update_method); + conn.setRequestHeader("Content-type","text/plain"); + conn.send("window resize " +screen_x+" "+screen_y+"\n"); +} + +function do_poll() { + if (urwid_id == null){ + alert("that's unpossible!"); + return; + } + if (window.XMLHttpRequest) { + conn = new XMLHttpRequest(); + } else if (window.ActiveXObject) { + conn = new ActiveXObject("Microsoft.XMLHTTP"); + } + conn.onreadystatechange = handle_recv; + conn.open("POST", document_location, true); + conn.setRequestHeader("X-Urwid-Method","polling"); + conn.setRequestHeader("X-Urwid-ID",urwid_id); + conn.setRequestHeader("Content-type","text/plain"); + conn.send("eh?"); +} + +function handle_recv() { + if( ! conn ){ return;} + if( conn.readyState != 4) { + return; + } + if( conn.status == 404 && urwid_id != null) { + set_status("Connection Closed"); + return; + } + if( conn.status == 403 && update_method == "polling" ) { + set_status("Server Refused Connection"); + alert("This server does not allow polling clients.\n\n" + + "Please use a web browser with multipart support " + + "such as Mozilla Firefox"); + return; + } + if( conn.status == 503 ) { + set_status("Connection Failed"); + alert("The server has reached its maximum number of "+ + "connections.\n\nPlease try again later."); + return; + } + if( conn.status != 200) { + set_status("Connection Failed"); + alert("Error from server: "+conn.statusText); + return; + } + if( urwid_id == null ){ + urwid_id = conn.getResponseHeader("X-Urwid-ID"); + if( send_queue_in != send_queue_out ){ + // keys waiting + do_send(); + } + if(update_method=="polling"){ + set_status("Polling"); + }else if(update_method=="multipart"){ + set_status("Connected"); + } + + } + + if( conn.responseText == "" ){ + if(update_method=="polling"){ + poll_again(); + } + return; // keepalive + } + if( conn.responseText == "Z" ){ + set_status("Connection Closed"); + update_method = null; + return; + } + + var text = document.getElementById('text'); + + var last_screen = Array(text.childNodes.length); + for( var i=0; i k ){ + text.replaceChild(ln, text.childNodes[k]); + }else{ + text.appendChild(ln); + } + k = k+1; + ln = document.createElement('span'); + }else if( f.charAt(0) == "<" ){ + line_number = parseInt(f.substr(1)); + if( line_number == k ){ + k = k +1; + continue; + } + var clone = last_screen[line_number].cloneNode(true); + if( text.childNodes.length > k ){ + text.replaceChild(clone, text.childNodes[k]); + }else{ + text.appendChild(clone); + } + k = k+1; + }else{ + var span=make_span(f.substr(2),f.charAt(0),f.charAt(1)); + ln.appendChild( span ); + } + } + for( var i=k; i < text.childNodes.length; i++ ){ + text.removeChild(last_screen[i]); + } + + if(update_method=="polling"){ + poll_again(); + } +} + +function poll_again(){ + if(conn.status == 200){ + setTimeout("do_poll();",poll_again_delay); + } +} + + +function load_web_display(){ + if( document.documentURI ){ + document_location = document.documentURI; + }else{ + document_location = document.location; + } + + document.onkeypress = body_keypress; + document.onkeydown = body_keydown; + document.onresize = body_resize; + + body_resize(); + send_queue_out = send_queue_in; // don't queue the first resize + + set_status("Connecting"); + setup_connection(); + + setTimeout("check_fontsize();",check_font_delay); +} + +function set_status( status ){ + var s = document.getElementById('status'); + var t = document.createTextNode(status); + s.replaceChild(t, s.firstChild); +} + +function make_span(s, fg, bg){ + d = document.createElement('span'); + d.style.backgroundColor = colours[bg]; + d.style.color = colours[fg]; + d.appendChild(document.createTextNode(s)); + + return d; +} + +function body_keydown(e){ + if (conn == null){ + return; + } + if (!e) var e = window.event; + if (e.keyCode) code = e.keyCode; + else if (e.which) code = e.which; + + var mod = ""; + var key; + + if( e.ctrlKey ){ mod = "ctrl " + mod; } + if( e.altKey || e.metaKey ){ mod = "meta " + mod; } + if( e.shiftKey && e.charCode == 0 ){ mod = "shift " + mod; } + + key = keycodes[code]; + + if( key != undefined ){ + lastkeydown = key; + send_key( mod + key ); + stop_key_event(e); + return false; + } +} + +function body_keypress(e){ + if (conn == null){ + return; + } + + if (!e) var e = window.event; + if (e.keyCode) code = e.keyCode; + else if (e.which) code = e.which; + + var mod = ""; + var key; + + if( e.ctrlKey ){ mod = "ctrl " + mod; } + if( e.altKey || e.metaKey ){ mod = "meta " + mod; } + if( e.shiftKey && e.charCode == 0 ){ mod = "shift " + mod; } + + if( e.charCode != null && e.charCode != 0 ){ + key = String.fromCharCode(e.charCode); + }else if( e.charCode == null ){ + key = String.fromCharCode(code); + }else{ + key = keycodes[code]; + if( key == undefined || lastkeydown == key ){ + lastkeydown = null; + stop_key_event(e); + return false; + } + } + + send_key( mod + key ); + stop_key_event(e); + return false; +} + +function stop_key_event(e){ + e.cancelBubble = true; + if( e.stopPropagation ){ + e.stopPropagation(); + } + if( e.preventDefault ){ + e.preventDefault(); + } +} + +function send_key( key ){ + if( (send_queue_in+1)%send_queue_max == send_queue_out ){ + // buffer overrun + return; + } + send_queue[send_queue_in] = key; + send_queue_in = (send_queue_in+1)%send_queue_max; + + if( urwid_id != null ){ + if (send_conn == undefined || send_conn.ready_state != 4 ){ + send_more(); + return; + } + do_send(); + } +} + +function do_send() { + if( ! urwid_id ){ return; } + if( ! update_method ){ return; } // connection closed + if( send_queue_in == send_queue_out ){ return; } + if( sending ){ + //var queue_delta = send_queue_in - send_queue_out; + //if( queue_delta < 0 ){ queue_delta += send_queue_max; } + //set_status("Sending (queued "+queue_delta+")"); + return; + } + try{ + sending = true; + //set_status("starting send"); + if( send_conn == null ){ + if (window.XMLHttpRequest) { + send_conn = new XMLHttpRequest(); + } else if (window.ActiveXObject) { + send_conn = new ActiveXObject("Microsoft.XMLHTTP"); + } + }else if( send_conn.status != 200) { + alert("Error from server: "+send_conn.statusText); + return; + }else if(send_conn.readyState != 4 ){ + alert("not ready on send connection"); + return; + } + } catch(e) { + alert(e); + sending = false; + return; + } + send_conn.open("POST", document_location, true); + send_conn.onreadystatechange = send_handle_recv; + send_conn.setRequestHeader("Content-type","text/plain"); + send_conn.setRequestHeader("X-Urwid-ID",urwid_id); + var tmp_send_queue_in = send_queue_in; + var out = null; + if( send_queue_out > tmp_send_queue_in ){ + out = send_queue.slice(send_queue_out).join("\n") + if( tmp_send_queue_in > 0 ){ + out += "\n" + send_queue.slice(0,tmp_send_queue_in).join("\n"); + } + }else{ + out = send_queue.slice(send_queue_out, + tmp_send_queue_in).join("\n"); + } + send_queue_out = tmp_send_queue_in; + //set_status("Sending"); + send_conn.send( out +"\n" ); +} + +function send_handle_recv() { + if( send_conn.readyState != 4) { + return; + } + if( send_conn.status == 404) { + set_status("Connection Closed"); + update_method = null; + return; + } + if( send_conn.status != 200) { + alert("Error from server: "+send_conn.statusText); + return; + } + + sending = false; + + if( send_queue_out != send_queue_in ){ + send_more(); + } +} + +function send_more(){ + setTimeout("do_send();",send_more_delay); +} + +function check_fontsize(){ + body_resize() + setTimeout("check_fontsize();",check_font_delay); +} + +function body_resize(){ + var t = document.getElementById('testchar'); + var t2 = document.getElementById('testchar2'); + var text = document.getElementById('text'); + + var window_width; + var window_height; + if (window.innerHeight) { + window_width = window.innerWidth; + window_height = window.innerHeight; + }else{ + window_width = document.documentElement.clientWidth; + window_height = document.documentElement.clientHeight; + //var z = "CI:"; for(var i in bod){z = z + " " + i;} alert(z); + } + + char_width = t.offsetLeft / 44; + var avail_width = window_width-18; + var avail_width_mod = avail_width % char_width; + var x_size = (avail_width - avail_width_mod)/char_width; + + char_height = t2.offsetTop - t.offsetTop; + var avail_height = window_height-text.offsetTop-10; + var avail_height_mod = avail_height % char_height; + var y_size = (avail_height - avail_height_mod)/char_height; + + text.style.width = x_size*char_width+"px"; + text.style.height = y_size*char_height+"px"; + + if( screen_x != x_size || screen_y != y_size ){ + send_key("window resize "+x_size+" "+y_size); + } + screen_x = x_size; + screen_y = y_size; +} diff --git a/python/user_packages/Python313/site-packages/urwid/display/_win32.py b/python/user_packages/Python313/site-packages/urwid/display/_win32.py new file mode 100644 index 0000000000000000000000000000000000000000..690c0ef3fffa73e4617e098b2757130142b6150d --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_win32.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import enum +import typing +from ctypes import POINTER, Structure, Union, windll +from ctypes.wintypes import BOOL, CHAR, DWORD, HANDLE, LPDWORD, SHORT, UINT, WCHAR, WORD + +# https://docs.microsoft.com/de-de/windows/console/getstdhandle +STD_INPUT_HANDLE = -10 +STD_OUTPUT_HANDLE = -11 + +# https://docs.microsoft.com/de-de/windows/console/setconsolemode +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 +DISABLE_NEWLINE_AUTO_RETURN = 0x0008 +ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 +ENABLE_WINDOW_INPUT = 0x0008 + + +class COORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/coord-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("X", SHORT), + ("Y", SHORT), + ] + + +class SMALL_RECT(Structure): + """https://docs.microsoft.com/en-us/windows/console/small-rect-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("Left", SHORT), + ("Top", SHORT), + ("Right", SHORT), + ("Bottom", SHORT), + ] + + +class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", WORD), + ("srWindow", SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] + + +class uChar(Union): + """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("AsciiChar", CHAR), + ("UnicodeChar", WCHAR), + ] + + +class KEY_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("bKeyDown", BOOL), + ("wRepeatCount", WORD), + ("wVirtualKeyCode", WORD), + ("wVirtualScanCode", WORD), + ("uChar", uChar), + ("dwControlKeyState", DWORD), + ] + + +class MOUSE_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("dwMousePosition", COORD), + ("dwButtonState", DWORD), + ("dwControlKeyState", DWORD), + ("dwEventFlags", DWORD), + ] + + +class MouseButtonState(enum.IntFlag): + """https://learn.microsoft.com/en-us/windows/console/mouse-event-record-str""" + + FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001 + RIGHTMOST_BUTTON_PRESSED = 0x0002 + FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004 + FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008 + FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010 + + +class MouseEventFlags(enum.IntFlag): + """https://learn.microsoft.com/en-us/windows/console/mouse-event-record-str""" + + BUTTON_PRESSED = 0x0000 # Default action, used in examples, but not in official enum + MOUSE_MOVED = 0x0001 + DOUBLE_CLICK = 0x0002 + MOUSE_WHEELED = 0x0004 + MOUSE_HWHEELED = 0x0008 + + +class WINDOW_BUFFER_SIZE_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/window-buffer-size-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [("dwSize", COORD)] + + +class MENU_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/menu-event-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [("dwCommandId", UINT)] + + +class FOCUS_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/focus-event-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [("bSetFocus", BOOL)] + + +class Event(Union): + """https://docs.microsoft.com/en-us/windows/console/input-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [ + ("KeyEvent", KEY_EVENT_RECORD), + ("MouseEvent", MOUSE_EVENT_RECORD), + ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD), + ("MenuEvent", MENU_EVENT_RECORD), + ("FocusEvent", FOCUS_EVENT_RECORD), + ] + + +class INPUT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/input-record-str""" + + _fields_: typing.ClassVar[list[tuple[str, type]]] = [("EventType", WORD), ("Event", Event)] + + +class EventType(enum.IntFlag): + KEY_EVENT = 0x0001 + MOUSE_EVENT = 0x0002 + WINDOW_BUFFER_SIZE_EVENT = 0x0004 + MENU_EVENT = 0x0008 + FOCUS_EVENT = 0x0010 + + +# https://docs.microsoft.com/de-de/windows/console/getstdhandle +GetStdHandle = windll.kernel32.GetStdHandle +GetStdHandle.argtypes = [DWORD] +GetStdHandle.restype = HANDLE + +# https://docs.microsoft.com/de-de/windows/console/getconsolemode +GetConsoleMode = windll.kernel32.GetConsoleMode +GetConsoleMode.argtypes = [HANDLE, LPDWORD] +GetConsoleMode.restype = BOOL + +# https://docs.microsoft.com/de-de/windows/console/setconsolemode +SetConsoleMode = windll.kernel32.SetConsoleMode +SetConsoleMode.argtypes = [HANDLE, DWORD] +SetConsoleMode.restype = BOOL + +# https://docs.microsoft.com/de-de/windows/console/readconsoleinput +ReadConsoleInputW = windll.kernel32.ReadConsoleInputW +# ReadConsoleInputW.argtypes = [HANDLE, POINTER(INPUT_RECORD), DWORD, LPDWORD] +ReadConsoleInputW.restype = BOOL + +# https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo +GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo +GetConsoleScreenBufferInfo.argtypes = [HANDLE, POINTER(CONSOLE_SCREEN_BUFFER_INFO)] +GetConsoleScreenBufferInfo.restype = BOOL diff --git a/python/user_packages/Python313/site-packages/urwid/display/_win32_raw_display.py b/python/user_packages/Python313/site-packages/urwid/display/_win32_raw_display.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5acb408ad77fc363fcb2ccae6bbab5ac3e700f --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/_win32_raw_display.py @@ -0,0 +1,267 @@ +# Urwid raw display module +# Copyright (C) 2004-2009 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Direct terminal UI implementation +""" + +from __future__ import annotations + +import contextlib +import functools +import logging +import selectors +import socket +import sys +import threading +import typing +from ctypes import byref +from ctypes.wintypes import DWORD + +from urwid import signals + +from . import _raw_display_base, _win32, escape +from .common import INPUT_DESCRIPTORS_CHANGED + +if typing.TYPE_CHECKING: + from collections.abc import Callable + + from urwid.event_loop import EventLoop + + +class Screen(_raw_display_base.Screen): + _term_input_file: socket.socket + + def __init__( + self, + input: socket.socket | None = None, # noqa: A002 # pylint: disable=redefined-builtin + output: typing.TextIO = sys.stdout, + ) -> None: + """Initialize a screen that directly prints escape codes to an output + terminal. + """ + if input is None: + input, self._send_input = socket.socketpair() # noqa: A001 + + super().__init__(input, output) + + _dwOriginalOutMode = None + _dwOriginalInMode = None + + def _start(self, alternate_buffer: bool = True) -> None: + """ + Initialize the screen and input mode. + + alternate_buffer -- use alternate screen buffer + """ + if alternate_buffer: + self.write(escape.SWITCH_TO_ALTERNATE_BUFFER) + self._rows_used = None + else: + self._rows_used = 0 + + handle_out = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) + handle_in = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) + self._dwOriginalOutMode = DWORD() + self._dwOriginalInMode = DWORD() + _win32.GetConsoleMode(handle_out, byref(self._dwOriginalOutMode)) + _win32.GetConsoleMode(handle_in, byref(self._dwOriginalInMode)) + # TODO: Restore on exit + + dword_out_mode = DWORD( + self._dwOriginalOutMode.value + | _win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING + | _win32.DISABLE_NEWLINE_AUTO_RETURN + ) + dword_in_mode = DWORD( + self._dwOriginalInMode.value | _win32.ENABLE_WINDOW_INPUT | _win32.ENABLE_VIRTUAL_TERMINAL_INPUT + ) + + if not (ok := _win32.SetConsoleMode(handle_out, dword_out_mode)): + raise RuntimeError(f"ConsoleMode set failed for output. Err: {ok!r}") + + if not (ok := _win32.SetConsoleMode(handle_in, dword_in_mode)): + raise RuntimeError(f"ConsoleMode set failed for input. Err: {ok!r}") + self._alternate_buffer = alternate_buffer + self._next_timeout = self.max_wait + + signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) + # restore mouse tracking to previous state + self._mouse_tracking(self._mouse_tracking_enabled) + + return super()._start() + + def _stop(self) -> None: + """ + Restore the screen. + """ + self.clear() + + signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED) + + self._stop_mouse_restore_buffer() + + handle_out = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) + handle_in = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) + + if not (ok := _win32.SetConsoleMode(handle_out, self._dwOriginalOutMode)): + raise RuntimeError(f"ConsoleMode set failed for output. Err: {ok!r}") + + if not (ok := _win32.SetConsoleMode(handle_in, self._dwOriginalInMode)): + raise RuntimeError(f"ConsoleMode set failed for input. Err: {ok!r}") + + super()._stop() + + def unhook_event_loop(self, event_loop: EventLoop) -> None: + """ + Remove any hooks added by hook_event_loop. + """ + if self._input_thread is not None: + self._input_thread.should_exit = True + + with contextlib.suppress(RuntimeError): + self._input_thread.join(5) + + self._input_thread = None + + for handle in self._current_event_loop_handles: + event_loop.remove_watch_file(handle) + + if self._input_timeout: + event_loop.remove_alarm(self._input_timeout) + self._input_timeout = None + + def hook_event_loop( + self, + event_loop: EventLoop, + callback: Callable[[list[str], list[int]], typing.Any], + ) -> None: + """ + Register the given callback with the event loop, to be called with new + input whenever it's available. The callback should be passed a list of + processed keys and a list of unprocessed keycodes. + + Subclasses may wish to use parse_input to wrap the callback. + """ + self._input_thread = ReadInputThread(self._send_input, lambda: self._sigwinch_handler(28)) + self._input_thread.start() + if hasattr(self, "get_input_nonblocking"): + wrapper = self._make_legacy_input_wrapper(event_loop, callback) + else: + + @functools.wraps(callback) + def wrapper() -> tuple[list[str], typing.Any] | None: + return self.parse_input(event_loop, callback, self.get_available_raw_input()) + + fds = self.get_input_descriptors() + handles = [event_loop.watch_file(fd if isinstance(fd, int) else fd.fileno(), wrapper) for fd in fds] + self._current_event_loop_handles = handles + + _input_thread: ReadInputThread | None = None + + def _read_raw_input(self, timeout: int) -> bytearray: + ready = self._wait_for_input_ready(timeout) + + fd = self._input_fileno() + chars = bytearray() + + if fd is None or fd not in ready: + return chars + + with selectors.DefaultSelector() as selector: + selector.register(fd, selectors.EVENT_READ) + + while selector.select(0): + chars.extend(self._term_input_file.recv(1024)) + + return chars + + def get_cols_rows(self) -> tuple[int, int]: + """Return the terminal dimensions (num columns, num rows).""" + y, x = super().get_cols_rows() + with contextlib.suppress(OSError): # Term size could not be determined + if hasattr(self._term_output_file, "fileno"): + if self._term_output_file != sys.stdout: + raise RuntimeError("Unexpected terminal output file") + handle = _win32.GetStdHandle(_win32.STD_OUTPUT_HANDLE) + info = _win32.CONSOLE_SCREEN_BUFFER_INFO() + + if _win32.GetConsoleScreenBufferInfo(handle, byref(info)): + # Fallback will be used in case of term size could not be determined + y, x = info.dwSize.Y, info.dwSize.X + + self.maxrow = y + return x, y + + +class ReadInputThread(threading.Thread): + name = "urwid Windows input reader" + daemon = True + should_exit: bool = False + + def __init__( + self, + input_socket: socket.socket, + resize: Callable[[], typing.Any], + ) -> None: + self._input = input_socket + self._resize = resize + self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__) + super().__init__() + + def run(self) -> None: + hIn = _win32.GetStdHandle(_win32.STD_INPUT_HANDLE) + MAX = 2048 + + read = DWORD(0) + arrtype = _win32.INPUT_RECORD * MAX + input_records = arrtype() + + while True: + _win32.ReadConsoleInputW(hIn, byref(input_records), MAX, byref(read)) + if self.should_exit: + return + for i in range(read.value): + inp = input_records[i] + if inp.EventType == _win32.EventType.KEY_EVENT: + if not inp.Event.KeyEvent.bKeyDown: + continue + + input_data = inp.Event.KeyEvent.uChar.UnicodeChar + # On Windows atomic press/release of modifier keys produce phantom input with code NULL. + # This input cannot be decoded and should be handled as garbage. + input_bytes = input_data.encode("utf-8") + if input_bytes != b"\x00": + self._input.send(input_bytes) + + elif inp.EventType == _win32.EventType.WINDOW_BUFFER_SIZE_EVENT: + self._resize() + else: + pass # TODO: handle mouse events + + +def _test(): + import doctest + + doctest.testmod() + + +if __name__ == "__main__": + _test() diff --git a/python/user_packages/Python313/site-packages/urwid/display/common.py b/python/user_packages/Python313/site-packages/urwid/display/common.py new file mode 100644 index 0000000000000000000000000000000000000000..54817a671028fdbe01a5c9207e9ba072e8a9341b --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/common.py @@ -0,0 +1,1189 @@ +# Urwid common display code +# Copyright (C) 2004-2011 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +from __future__ import annotations + +import abc +import logging +import os +import sys +import typing +import warnings + +from urwid import signals +from urwid.util import StoppingContext, int_scale + +if typing.TYPE_CHECKING: + from collections.abc import Iterable, Sequence + + from typing_extensions import Literal, Self + + from urwid import Canvas + +IS_WINDOWS = sys.platform == "win32" + +# for replacing unprintable bytes with '?' +UNPRINTABLE_TRANS_TABLE = b"?" * 32 + bytes(range(32, 256)) + + +# signals sent by BaseScreen +UPDATE_PALETTE_ENTRY = "update palette entry" +INPUT_DESCRIPTORS_CHANGED = "input descriptors changed" + + +# AttrSpec internal values +_BASIC_START = 0 # first index of basic color aliases +_CUBE_START = 16 # first index of color cube +_CUBE_SIZE_256 = 6 # one side of the color cube +_GRAY_SIZE_256 = 24 +_GRAY_START_256 = _CUBE_SIZE_256**3 + _CUBE_START +_CUBE_WHITE_256 = _GRAY_START_256 - 1 +_CUBE_SIZE_88 = 4 +_GRAY_SIZE_88 = 8 +_GRAY_START_88 = _CUBE_SIZE_88**3 + _CUBE_START +_CUBE_WHITE_88 = _GRAY_START_88 - 1 +_CUBE_BLACK = _CUBE_START + +# values copied from xterm 256colres.h: +_CUBE_STEPS_256 = [0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF] +_GRAY_STEPS_256 = [ + 0x08, + 0x12, + 0x1C, + 0x26, + 0x30, + 0x3A, + 0x44, + 0x4E, + 0x58, + 0x62, + 0x6C, + 0x76, + 0x80, + 0x84, + 0x94, + 0x9E, + 0xA8, + 0xB2, + 0xBC, + 0xC6, + 0xD0, + 0xDA, + 0xE4, + 0xEE, +] +# values copied from xterm 88colres.h: +_CUBE_STEPS_88 = [0x00, 0x8B, 0xCD, 0xFF] +_GRAY_STEPS_88 = [0x2E, 0x5C, 0x73, 0x8B, 0xA2, 0xB9, 0xD0, 0xE7] +# values copied from X11/rgb.txt and XTerm-col.ad: +_BASIC_COLOR_VALUES = [ + (0, 0, 0), + (205, 0, 0), + (0, 205, 0), + (205, 205, 0), + (0, 0, 238), + (205, 0, 205), + (0, 205, 205), + (229, 229, 229), + (127, 127, 127), + (255, 0, 0), + (0, 255, 0), + (255, 255, 0), + (0x5C, 0x5C, 0xFF), + (255, 0, 255), + (0, 255, 255), + (255, 255, 255), +] + +_COLOR_VALUES_256 = ( + _BASIC_COLOR_VALUES + + [(r, g, b) for r in _CUBE_STEPS_256 for g in _CUBE_STEPS_256 for b in _CUBE_STEPS_256] + + [(gr, gr, gr) for gr in _GRAY_STEPS_256] +) +_COLOR_VALUES_88 = ( + _BASIC_COLOR_VALUES + + [(r, g, b) for r in _CUBE_STEPS_88 for g in _CUBE_STEPS_88 for b in _CUBE_STEPS_88] + + [(gr, gr, gr) for gr in _GRAY_STEPS_88] +) + +if len(_COLOR_VALUES_256) != 256: + raise RuntimeError(_COLOR_VALUES_256) +if len(_COLOR_VALUES_88) != 88: + raise RuntimeError(_COLOR_VALUES_88) + +# fmt: off +_FG_COLOR_MASK = 0x000000ffffff +_BG_COLOR_MASK = 0xffffff000000 +_FG_BASIC_COLOR = 0x1000000000000 +_FG_HIGH_COLOR = 0x2000000000000 +_FG_TRUE_COLOR = 0x4000000000000 +_BG_BASIC_COLOR = 0x8000000000000 +_BG_HIGH_COLOR = 0x10000000000000 +_BG_TRUE_COLOR = 0x20000000000000 +_BG_SHIFT = 24 +_HIGH_88_COLOR = 0x40000000000000 +_HIGH_TRUE_COLOR = 0x80000000000000 +_STANDOUT = 0x100000000000000 +_UNDERLINE = 0x200000000000000 +_BOLD = 0x400000000000000 +_BLINK = 0x800000000000000 +_ITALICS = 0x1000000000000000 +_STRIKETHROUGH = 0x2000000000000000 +# fmt: on + +_FG_MASK = ( + _FG_COLOR_MASK + | _FG_BASIC_COLOR + | _FG_HIGH_COLOR + | _STANDOUT + | _UNDERLINE + | _BLINK + | _BOLD + | _ITALICS + | _STRIKETHROUGH +) +_BG_MASK = _BG_COLOR_MASK | _BG_BASIC_COLOR | _BG_HIGH_COLOR + +DEFAULT = "default" +BLACK = "black" +DARK_RED = "dark red" +DARK_GREEN = "dark green" +BROWN = "brown" +DARK_BLUE = "dark blue" +DARK_MAGENTA = "dark magenta" +DARK_CYAN = "dark cyan" +LIGHT_GRAY = "light gray" +DARK_GRAY = "dark gray" +LIGHT_RED = "light red" +LIGHT_GREEN = "light green" +YELLOW = "yellow" +LIGHT_BLUE = "light blue" +LIGHT_MAGENTA = "light magenta" +LIGHT_CYAN = "light cyan" +WHITE = "white" + +_BASIC_COLORS = [ + BLACK, + DARK_RED, + DARK_GREEN, + BROWN, + DARK_BLUE, + DARK_MAGENTA, + DARK_CYAN, + LIGHT_GRAY, + DARK_GRAY, + LIGHT_RED, + LIGHT_GREEN, + YELLOW, + LIGHT_BLUE, + LIGHT_MAGENTA, + LIGHT_CYAN, + WHITE, +] + +_ATTRIBUTES = { + "bold": _BOLD, + "italics": _ITALICS, + "underline": _UNDERLINE, + "blink": _BLINK, + "standout": _STANDOUT, + "strikethrough": _STRIKETHROUGH, +} + + +def _value_lookup_table(values: Sequence[int], size: int) -> list[int]: + """ + Generate a lookup table for finding the closest item in values. + Lookup returns (index into values)+1 + + values -- list of values in ascending order, all < size + size -- size of lookup table and maximum value + + >>> _value_lookup_table([0, 7, 9], 10) + [0, 0, 0, 0, 1, 1, 1, 1, 2, 2] + """ + + middle_values = [0] + [(values[i] + values[i + 1] + 1) // 2 for i in range(len(values) - 1)] + [size] + lookup_table = [] + for i in range(len(middle_values) - 1): + count = middle_values[i + 1] - middle_values[i] + lookup_table.extend([i] * count) + return lookup_table + + +_CUBE_256_LOOKUP = _value_lookup_table(_CUBE_STEPS_256, 256) +_GRAY_256_LOOKUP = _value_lookup_table([0, *_GRAY_STEPS_256, 255], 256) +_CUBE_88_LOOKUP = _value_lookup_table(_CUBE_STEPS_88, 256) +_GRAY_88_LOOKUP = _value_lookup_table([0, *_GRAY_STEPS_88, 255], 256) + +# convert steps to values that will be used by string versions of the colors +# 1 hex digit for rgb and 0..100 for grayscale +_CUBE_STEPS_256_16 = [int_scale(n, 0x100, 0x10) for n in _CUBE_STEPS_256] +_GRAY_STEPS_256_101 = [int_scale(n, 0x100, 101) for n in _GRAY_STEPS_256] +_CUBE_STEPS_88_16 = [int_scale(n, 0x100, 0x10) for n in _CUBE_STEPS_88] +_GRAY_STEPS_88_101 = [int_scale(n, 0x100, 101) for n in _GRAY_STEPS_88] + +# create lookup tables for 1 hex digit rgb and 0..100 for grayscale values +_CUBE_256_LOOKUP_16 = [_CUBE_256_LOOKUP[int_scale(n, 16, 0x100)] for n in range(16)] +_GRAY_256_LOOKUP_101 = [_GRAY_256_LOOKUP[int_scale(n, 101, 0x100)] for n in range(101)] +_CUBE_88_LOOKUP_16 = [_CUBE_88_LOOKUP[int_scale(n, 16, 0x100)] for n in range(16)] +_GRAY_88_LOOKUP_101 = [_GRAY_88_LOOKUP[int_scale(n, 101, 0x100)] for n in range(101)] + + +# The functions _gray_num_256() and _gray_num_88() do not include the gray +# values from the color cube so that the gray steps are an even width. +# The color cube grays are available by using the rgb functions. Pure +# white and black are taken from the color cube, since the gray range does +# not include them, and the basic colors are more likely to have been +# customized by an end-user. + + +def _gray_num_256(gnum: int) -> int: + """Return ths color number for gray number gnum. + + Color cube black and white are returned for 0 and 25 respectively + since those values aren't included in the gray scale. + + """ + # grays start from index 1 + gnum -= 1 + + if gnum < 0: + return _CUBE_BLACK + if gnum >= _GRAY_SIZE_256: + return _CUBE_WHITE_256 + return _GRAY_START_256 + gnum + + +def _gray_num_88(gnum: int) -> int: + """Return ths color number for gray number gnum. + + Color cube black and white are returned for 0 and 9 respectively + since those values aren't included in the gray scale. + + """ + # gnums start from index 1 + gnum -= 1 + + if gnum < 0: + return _CUBE_BLACK + if gnum >= _GRAY_SIZE_88: + return _CUBE_WHITE_88 + return _GRAY_START_88 + gnum + + +def _color_desc_true(num: int) -> str: + return f"#{num:06x}" + + +def _color_desc_256(num: int) -> str: + """ + Return a string description of color number num. + 0..15 -> 'h0'..'h15' basic colors (as high-colors) + 16..231 -> '#000'..'#fff' color cube colors + 232..255 -> 'g3'..'g93' grays + + >>> _color_desc_256(15) + 'h15' + >>> _color_desc_256(16) + '#000' + >>> _color_desc_256(17) + '#006' + >>> _color_desc_256(230) + '#ffd' + >>> _color_desc_256(233) + 'g7' + >>> _color_desc_256(234) + 'g11' + + """ + if not 0 <= num < 256: + raise ValueError(num) + if num < _CUBE_START: + return f"h{num:d}" + if num < _GRAY_START_256: + num -= _CUBE_START + b, num = num % _CUBE_SIZE_256, num // _CUBE_SIZE_256 + g, num = num % _CUBE_SIZE_256, num // _CUBE_SIZE_256 + r = num % _CUBE_SIZE_256 + return f"#{_CUBE_STEPS_256_16[r]:x}{_CUBE_STEPS_256_16[g]:x}{_CUBE_STEPS_256_16[b]:x}" + return f"g{_GRAY_STEPS_256_101[num - _GRAY_START_256]:d}" + + +def _color_desc_88(num: int) -> str: + """ + Return a string description of color number num. + 0..15 -> 'h0'..'h15' basic colors (as high-colors) + 16..79 -> '#000'..'#fff' color cube colors + 80..87 -> 'g18'..'g90' grays + + >>> _color_desc_88(15) + 'h15' + >>> _color_desc_88(16) + '#000' + >>> _color_desc_88(17) + '#008' + >>> _color_desc_88(78) + '#ffc' + >>> _color_desc_88(81) + 'g36' + >>> _color_desc_88(82) + 'g45' + + """ + if not 0 < num < 88: + raise ValueError(num) + if num < _CUBE_START: + return f"h{num:d}" + if num < _GRAY_START_88: + num -= _CUBE_START + b, num = num % _CUBE_SIZE_88, num // _CUBE_SIZE_88 + g, r = num % _CUBE_SIZE_88, num // _CUBE_SIZE_88 + return f"#{_CUBE_STEPS_88_16[r]:x}{_CUBE_STEPS_88_16[g]:x}{_CUBE_STEPS_88_16[b]:x}" + return f"g{_GRAY_STEPS_88_101[num - _GRAY_START_88]:d}" + + +def _parse_color_true(desc: str) -> int | None: + if (c := _parse_color_256(desc)) is not None: + (r, g, b) = _COLOR_VALUES_256[c] + return (r << 16) + (g << 8) + b + + if not desc.startswith("#"): + return None + + if len(desc) == 7: + h = desc[1:] + return int(h, 16) + + if len(desc) == 4: + h = f"0x{desc[1]}0{desc[2]}0{desc[3]}" + return int(h, 16) + + return None + + +def _parse_color_256(desc: str) -> int | None: + """ + Return a color number for the description desc. + 'h0'..'h255' -> 0..255 actual color number + '#000'..'#fff' -> 16..231 color cube colors + 'g0'..'g100' -> 16, 232..255, 231 grays and color cube black/white + 'g#00'..'g#ff' -> 16, 232...255, 231 gray and color cube black/white + + Returns None if desc is invalid. + + >>> _parse_color_256("h142") + 142 + >>> _parse_color_256("#f00") + 196 + >>> _parse_color_256("g100") + 231 + >>> _parse_color_256("g#80") + 244 + """ + if len(desc) > 4: + # keep the length within reason before parsing + return None + try: + if desc.startswith("h"): + # high-color number + num = int(desc[1:], 10) + if num < 0 or num > 255: + return None + return num + + if desc.startswith("#") and len(desc) == 4: + # color-cube coordinates + if (rgb := int(desc[1:], 16)) >= 0: + b, rgb = rgb % 16, rgb // 16 + g, r = rgb % 16, rgb // 16 + # find the closest rgb values + r = _CUBE_256_LOOKUP_16[r] + g = _CUBE_256_LOOKUP_16[g] + b = _CUBE_256_LOOKUP_16[b] + return _CUBE_START + (r * _CUBE_SIZE_256 + g) * _CUBE_SIZE_256 + b + + return None + + # Only remaining possibility is gray value + if desc.startswith("g#"): + # hex value 00..ff + gray = int(desc[2:], 16) # noqa: FURB166 + if gray < 0 or gray > 255: + return None + gray = _GRAY_256_LOOKUP[gray] + elif desc.startswith("g"): + # decimal value 0..100 + gray = int(desc[1:], 10) + if gray < 0 or gray > 100: + return None + gray = _GRAY_256_LOOKUP_101[gray] + else: + return None + if gray == 0: + return _CUBE_BLACK + gray -= 1 + if gray == _GRAY_SIZE_256: + return _CUBE_WHITE_256 + return _GRAY_START_256 + gray + + except ValueError: + return None + + +def _true_to_256(desc: str) -> str | None: + if not (desc.startswith("#") and len(desc) == 7): + return None + + c256 = _parse_color_256("#" + "".join(format(int(x, 16) // 16, "x") for x in (desc[1:3], desc[3:5], desc[5:7]))) + return _color_desc_256(c256) + + +def _parse_color_88(desc: str) -> int | None: + """ + Return a color number for the description desc. + 'h0'..'h87' -> 0..87 actual color number + '#000'..'#fff' -> 16..79 color cube colors + 'g0'..'g100' -> 16, 80..87, 79 grays and color cube black/white + 'g#00'..'g#ff' -> 16, 80...87, 79 gray and color cube black/white + + Returns None if desc is invalid. + + >>> _parse_color_88("h142") + >>> _parse_color_88("h42") + 42 + >>> _parse_color_88("#f00") + 64 + >>> _parse_color_88("g100") + 79 + >>> _parse_color_88("g#80") + 83 + """ + if len(desc) == 7: + desc = desc[0:2] + desc[3] + desc[5] + if len(desc) > 4: + # keep the length within reason before parsing + return None + try: + if desc.startswith("h"): + # high-color number + num = int(desc[1:], 10) + if num < 0 or num > 87: + return None + return num + + if desc.startswith("#") and len(desc) == 4: + # color-cube coordinates + if (rgb := int(desc[1:], 16)) >= 0: + b, rgb = rgb % 16, rgb // 16 + g, r = rgb % 16, rgb // 16 + # find the closest rgb values + r = _CUBE_88_LOOKUP_16[r] + g = _CUBE_88_LOOKUP_16[g] + b = _CUBE_88_LOOKUP_16[b] + return _CUBE_START + (r * _CUBE_SIZE_88 + g) * _CUBE_SIZE_88 + b + + return None + + # Only remaining possibility is gray value + if desc.startswith("g#"): + # hex value 00..ff + gray = int(desc[2:], 16) # noqa: FURB166 + if gray < 0 or gray > 255: + return None + gray = _GRAY_88_LOOKUP[gray] + elif desc.startswith("g"): + # decimal value 0..100 + gray = int(desc[1:], 10) + if gray < 0 or gray > 100: + return None + gray = _GRAY_88_LOOKUP_101[gray] + else: + return None + if gray == 0: + return _CUBE_BLACK + gray -= 1 + if gray == _GRAY_SIZE_88: + return _CUBE_WHITE_88 + return _GRAY_START_88 + gray + + except ValueError: + return None + + +class AttrSpecError(Exception): + pass + + +class AttrSpec: + __slots__ = ("__value",) + + def __init__(self, fg: str, bg: str, colors: Literal[1, 16, 88, 256, 16777216] = 256) -> None: + """ + fg -- a string containing a comma-separated foreground color + and settings + + Color values: + 'default' (use the terminal's default foreground), + 'black', 'dark red', 'dark green', 'brown', 'dark blue', + 'dark magenta', 'dark cyan', 'light gray', 'dark gray', + 'light red', 'light green', 'yellow', 'light blue', + 'light magenta', 'light cyan', 'white' + + High-color example values: + '#009' (0% red, 0% green, 60% red, like HTML colors) + '#23facc' (RRGGBB hex color code) + '#fcc' (100% red, 80% green, 80% blue) + 'g40' (40% gray, decimal), 'g#cc' (80% gray, hex), + '#000', 'g0', 'g#00' (black), + '#fff', 'g100', 'g#ff' (white) + 'h8' (color number 8), 'h255' (color number 255) + + Setting: + 'bold', 'italics', 'underline', 'blink', 'standout', + 'strikethrough' + + Some terminals use 'bold' for bright colors. Most terminals + ignore the 'blink' setting. If the color is not given then + 'default' will be assumed. + + bg -- a string containing the background color + + Color values: + 'default' (use the terminal's default background), + 'black', 'dark red', 'dark green', 'brown', 'dark blue', + 'dark magenta', 'dark cyan', 'light gray' + + High-color exaples: + see fg examples above + + An empty string will be treated the same as 'default'. + + colors -- the maximum colors available for the specification + + Valid values include: 1, 16, 88, 256, and 2**24. High-color + values are only usable with 88, 256, or 2**24 colors. With + 1 color only the foreground settings may be used. + + >>> AttrSpec("dark red", "light gray", 16) + AttrSpec('dark red', 'light gray') + >>> AttrSpec("yellow, underline, bold", "dark blue") + AttrSpec('yellow,bold,underline', 'dark blue') + >>> AttrSpec("#ddb", "#004", 256) # closest colors will be found + AttrSpec('#dda', '#006') + >>> AttrSpec("#ddb", "#004", 88) + AttrSpec('#ccc', '#000', colors=88) + """ + if colors not in {1, 16, 88, 256, 2**24}: + raise AttrSpecError(f"invalid number of colors ({colors:d}).") + self.__value = 0 | _HIGH_88_COLOR * (colors == 88) | _HIGH_TRUE_COLOR * (colors == 2**24) + self.__set_foreground(fg) + self.__set_background(bg) + if self.colors > colors: + raise AttrSpecError( + f"foreground/background ({fg!r}/{bg!r}) require more colors than have been specified ({colors:d})." + ) + + def copy_modified( + self, + fg: str | None = None, + bg: str | None = None, + colors: Literal[1, 16, 88, 256, 16777216] | None = None, + ) -> Self: + if fg is None: + foreground = self.foreground + else: + foreground = fg + + if bg is None: + background = self.background + else: + background = bg + + if colors is None: + new_colors = self.colors + else: + new_colors = colors + + return self.__class__(foreground, background, new_colors) + + def __hash__(self) -> int: + """Instance is immutable and hashable.""" + return hash((self.__class__, self.__value)) + + @property + def _value(self) -> int: + """Read-only value access.""" + return self.__value + + @property + def foreground_basic(self) -> bool: + return self.__value & _FG_BASIC_COLOR != 0 + + @property + def foreground_high(self) -> bool: + return self.__value & _FG_HIGH_COLOR != 0 + + @property + def foreground_true(self) -> bool: + return self.__value & _FG_TRUE_COLOR != 0 + + @property + def foreground_number(self) -> int: + return self.__value & _FG_COLOR_MASK + + @property + def background_basic(self) -> bool: + return self.__value & _BG_BASIC_COLOR != 0 + + @property + def background_high(self) -> bool: + return self.__value & _BG_HIGH_COLOR != 0 + + @property + def background_true(self) -> bool: + return self.__value & _BG_TRUE_COLOR != 0 + + @property + def background_number(self) -> int: + return (self.__value & _BG_COLOR_MASK) >> _BG_SHIFT + + @property + def italics(self) -> bool: + return self.__value & _ITALICS != 0 + + @property + def bold(self) -> bool: + return self.__value & _BOLD != 0 + + @property + def underline(self) -> bool: + return self.__value & _UNDERLINE != 0 + + @property + def blink(self) -> bool: + return self.__value & _BLINK != 0 + + @property + def standout(self) -> bool: + return self.__value & _STANDOUT != 0 + + @property + def strikethrough(self) -> bool: + return self.__value & _STRIKETHROUGH != 0 + + @property + def colors(self) -> int: + """ + Return the maximum colors required for this object. + + Returns 256, 88, 16 or 1. + """ + if self.__value & _HIGH_88_COLOR: + return 88 + if self.__value & (_BG_HIGH_COLOR | _FG_HIGH_COLOR): + return 256 + if self.__value & (_BG_TRUE_COLOR | _FG_TRUE_COLOR): + return 2**24 + if self.__value & (_BG_BASIC_COLOR | _FG_BASIC_COLOR): + return 16 + return 1 + + def __repr__(self) -> str: + """ + Return an executable python representation of the AttrSpec + object. + """ + args = f"{self.foreground!r}, {self.background!r}" + if self.colors == 88: + # 88-color mode is the only one that is handled differently + args = f"{args}, colors=88" + return f"{self.__class__.__name__}({args})" + + def _foreground_color(self) -> str: + """Return only the color component of the foreground.""" + if not (self.foreground_basic or self.foreground_high or self.foreground_true): + return "default" + if self.foreground_basic: + return _BASIC_COLORS[self.foreground_number] + if self.colors == 88: + return _color_desc_88(self.foreground_number) + if self.colors == 2**24: + return _color_desc_true(self.foreground_number) + return _color_desc_256(self.foreground_number) + + @property + def foreground(self) -> str: + return ( + self._foreground_color() + + ",bold" * self.bold + + ",italics" * self.italics + + ",standout" * self.standout + + ",blink" * self.blink + + ",underline" * self.underline + + ",strikethrough" * self.strikethrough + ) + + def __set_foreground(self, foreground: str) -> None: + color = None + flags = 0 + # handle comma-separated foreground + for part in foreground.split(","): + part = part.strip() # noqa: PLW2901 + if part in _ATTRIBUTES: + # parse and store "settings"/attributes in flags + if flags & _ATTRIBUTES[part]: + raise AttrSpecError(f"Setting {part!r} specified more than once in foreground ({foreground!r})") + flags |= _ATTRIBUTES[part] + continue + # past this point we must be specifying a color + if part in {"", "default"}: + scolor = 0 + elif part in _BASIC_COLORS: + scolor = _BASIC_COLORS.index(part) + flags |= _FG_BASIC_COLOR + elif self.__value & _HIGH_88_COLOR: + scolor = _parse_color_88(part) + flags |= _FG_HIGH_COLOR + elif self.__value & _HIGH_TRUE_COLOR: + scolor = _parse_color_true(part) + flags |= _FG_TRUE_COLOR + else: + scolor = _parse_color_256(_true_to_256(part) or part) + flags |= _FG_HIGH_COLOR + # _parse_color_*() return None for unrecognized colors + if scolor is None: + raise AttrSpecError(f"Unrecognised color specification {part!r} in foreground ({foreground!r})") + if color is not None: + raise AttrSpecError(f"More than one color given for foreground ({foreground!r})") + color = scolor + if color is None: + color = 0 + self.__value = (self.__value & ~_FG_MASK) | color | flags + + @property + def background(self) -> str: + """Return the background color.""" + if not (self.background_basic or self.background_high or self.background_true): + return "default" + if self.background_basic: + return _BASIC_COLORS[self.background_number] + if self.__value & _HIGH_88_COLOR: + return _color_desc_88(self.background_number) + if self.colors == 2**24: + return _color_desc_true(self.background_number) + return _color_desc_256(self.background_number) + + def __set_background(self, background: str) -> None: + flags = 0 + if background in {"", "default"}: + color = 0 + elif background in _BASIC_COLORS: + color = _BASIC_COLORS.index(background) + flags |= _BG_BASIC_COLOR + elif self.__value & _HIGH_88_COLOR: + color = _parse_color_88(background) + flags |= _BG_HIGH_COLOR + elif self.__value & _HIGH_TRUE_COLOR: + color = _parse_color_true(background) + flags |= _BG_TRUE_COLOR + else: + color = _parse_color_256(_true_to_256(background) or background) + flags |= _BG_HIGH_COLOR + if color is None: + raise AttrSpecError(f"Unrecognised color specification in background ({background!r})") + self.__value = (self.__value & ~_BG_MASK) | (color << _BG_SHIFT) | flags + + def get_rgb_values(self) -> tuple[int | None, int | None, int | None, int | None, int | None, int | None]: + """ + Return (fg_red, fg_green, fg_blue, bg_red, bg_green, bg_blue) color + components. Each component is in the range 0-255. Values are taken + from the XTerm defaults and may not exactly match the user's terminal. + + If the foreground or background is 'default' then all their compenents + will be returned as None. + + >>> AttrSpec("yellow", "#ccf", colors=88).get_rgb_values() + (255, 255, 0, 205, 205, 255) + >>> AttrSpec("default", "g92").get_rgb_values() + (None, None, None, 238, 238, 238) + """ + if not (self.foreground_basic or self.foreground_high or self.foreground_true): + vals = (None, None, None) + elif self.colors == 88: + if self.foreground_number >= 88: + raise ValueError(f"Invalid AttrSpec _value: {self.foreground_number!r}") + vals = _COLOR_VALUES_88[self.foreground_number] + elif self.colors == 2**24: + h = f"{self.foreground_number:06x}" + vals = tuple(int(x, 16) for x in (h[0:2], h[2:4], h[4:6])) + else: + vals = _COLOR_VALUES_256[self.foreground_number] + + if not (self.background_basic or self.background_high or self.background_true): + return (*vals, None, None, None) + if self.colors == 88: + if self.background_number >= 88: + raise ValueError(f"Invalid AttrSpec _value: {self.background_number!r}") + return vals + _COLOR_VALUES_88[self.background_number] + if self.colors == 2**24: + h = f"{self.background_number:06x}" + return vals + tuple(int(x, 16) for x in (h[0:2], h[2:4], h[4:6])) + + return vals + _COLOR_VALUES_256[self.background_number] + + def __eq__(self, other: object) -> bool: + return isinstance(other, AttrSpec) and self.__value == other._value + + def __ne__(self, other: object) -> bool: + return not self == other + + +class RealTerminal: + def __init__(self) -> None: + super().__init__() + self._signal_keys_set = False + self._old_signal_keys = None + + if IS_WINDOWS: + + def tty_signal_keys( + self, + intr: Literal["undefined"] | int | None = None, + quit: Literal["undefined"] | int | None = None, # noqa: A002 # pylint: disable=redefined-builtin + start: Literal["undefined"] | int | None = None, + stop: Literal["undefined"] | int | None = None, + susp: Literal["undefined"] | int | None = None, + fileno: int | None = None, + ): + """ + Read and/or set the tty's signal character settings. + This function returns the current settings as a tuple. + + Use the string 'undefined' to unmap keys from their signals. + The value None is used when no change is being made. + Setting signal keys is done using the integer ascii + code for the key, eg. 3 for CTRL+C. + + If this function is called after start() has been called + then the original settings will be restored when stop() + is called. + """ + return () + + else: + + def tty_signal_keys( + self, + intr: Literal["undefined"] | int | None = None, + quit: Literal["undefined"] | int | None = None, # noqa: A002 # pylint: disable=redefined-builtin + start: Literal["undefined"] | int | None = None, + stop: Literal["undefined"] | int | None = None, + susp: Literal["undefined"] | int | None = None, + fileno: int | None = None, + ): + """ + Read and/or set the tty's signal character settings. + This function returns the current settings as a tuple. + + Use the string 'undefined' to unmap keys from their signals. + The value None is used when no change is being made. + Setting signal keys is done using the integer ascii + code for the key, eg. 3 for CTRL+C. + + If this function is called after start() has been called + then the original settings will be restored when stop() + is called. + """ + + import termios + + if fileno is None: + fileno = sys.stdin.fileno() + if not os.isatty(fileno): + return None + + tattr = termios.tcgetattr(fileno) + sattr = tattr[6] + skeys = ( + sattr[termios.VINTR], + sattr[termios.VQUIT], + sattr[termios.VSTART], + sattr[termios.VSTOP], + sattr[termios.VSUSP], + ) + + if intr == "undefined": + intr = 0 + if quit == "undefined": + quit = 0 # noqa: A001 + if start == "undefined": + start = 0 + if stop == "undefined": + stop = 0 + if susp == "undefined": + susp = 0 + + if intr is not None: + tattr[6][termios.VINTR] = intr + if quit is not None: + tattr[6][termios.VQUIT] = quit + if start is not None: + tattr[6][termios.VSTART] = start + if stop is not None: + tattr[6][termios.VSTOP] = stop + if susp is not None: + tattr[6][termios.VSUSP] = susp + + if any(item is not None for item in (intr, quit, start, stop, susp)): + termios.tcsetattr(fileno, termios.TCSADRAIN, tattr) + self._signal_keys_set = True + + return skeys + + +class ScreenError(Exception): + pass + + +class BaseScreen(abc.ABC, metaclass=signals.MetaSignals): + """ + Base class for Screen classes (raw_display.Screen, ..., etc.) + """ + + signals: typing.ClassVar[list[str]] = [UPDATE_PALETTE_ENTRY, INPUT_DESCRIPTORS_CHANGED] + + def __init__(self) -> None: + super().__init__() + + self.logger = logging.getLogger(f"{self.__class__.__module__}.{self.__class__.__name__}") + + self._palette: dict[str | None, tuple[AttrSpec, AttrSpec, AttrSpec, AttrSpec, AttrSpec]] = {} + self._started: bool = False + + @property + def started(self) -> bool: + return self._started + + def start(self, *args, **kwargs) -> StoppingContext: + """Set up the screen. If the screen has already been started, does + nothing. + + May be used as a context manager, in which case :meth:`stop` will + automatically be called at the end of the block: + + with screen.start(): + ... + + You shouldn't override this method in a subclass; instead, override + :meth:`_start`. + """ + if not self._started: + self._started = True + self._start(*args, **kwargs) + return StoppingContext(self) + + def _start(self) -> None: + pass + + def stop(self) -> None: + if self._started: + self._stop() + self._started = False + + def _stop(self) -> None: + pass + + def run_wrapper(self, fn, *args, **kwargs) -> None: + """Start the screen, call a function, then stop the screen. Extra + arguments are passed to `start`. + + Deprecated in favor of calling `start` as a context manager. + """ + warnings.warn( + "run_wrapper is deprecated in favor of calling `start` as a context manager.", + DeprecationWarning, + stacklevel=3, + ) + with self.start(*args, **kwargs): + return fn() + + def set_mouse_tracking(self, enable: bool = True) -> None: + pass + + @abc.abstractmethod + def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: + pass + + def clear(self) -> None: + """Clear the screen if possible. + + Force the screen to be completely repainted on the next call to draw_screen(). + """ + + def get_cols_rows(self) -> tuple[int, int]: + """Return the terminal dimensions (num columns, num rows). + + Default (fallback) is 80x24. + """ + return 80, 24 + + def register_palette( + self, + palette: Iterable[ + tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str] + ], + ) -> None: + """Register a set of palette entries. + + palette -- a list of (name, like_other_name) or + (name, foreground, background, mono, foreground_high, background_high) tuples + + The (name, like_other_name) format will copy the settings + from the palette entry like_other_name, which must appear + before this tuple in the list. + + The mono and foreground/background_high values are + optional ie. the second tuple format may have 3, 4 or 6 + values. See register_palette_entry() for a description + of the tuple values. + """ + + for item in palette: + if len(item) in {3, 4, 6}: + self.register_palette_entry(*item) + continue + if len(item) != 2: + raise ScreenError(f"Invalid register_palette entry: {item!r}") + name, like_name = item + if like_name not in self._palette: + raise ScreenError(f"palette entry '{like_name}' doesn't exist") + self._palette[name] = self._palette[like_name] + + def register_palette_entry( + self, + name: str | None, + foreground: str, + background: str, + mono: str | None = None, + foreground_high: str | None = None, + background_high: str | None = None, + ) -> None: + """Register a single palette entry. + + name -- new entry/attribute name + + foreground -- a string containing a comma-separated foreground + color and settings + + Color values: + 'default' (use the terminal's default foreground), + 'black', 'dark red', 'dark green', 'brown', 'dark blue', + 'dark magenta', 'dark cyan', 'light gray', 'dark gray', + 'light red', 'light green', 'yellow', 'light blue', + 'light magenta', 'light cyan', 'white' + + Settings: + 'bold', 'underline', 'blink', 'standout', 'strikethrough' + + Some terminals use 'bold' for bright colors. Most terminals + ignore the 'blink' setting. If the color is not given then + 'default' will be assumed. + + background -- a string containing the background color + + Background color values: + 'default' (use the terminal's default background), + 'black', 'dark red', 'dark green', 'brown', 'dark blue', + 'dark magenta', 'dark cyan', 'light gray' + + mono -- a comma-separated string containing monochrome terminal + settings (see "Settings" above.) + + None = no terminal settings (same as 'default') + + foreground_high -- a string containing a comma-separated + foreground color and settings, standard foreground + colors (see "Color values" above) or high-colors may + be used + + High-color example values: + '#009' (0% red, 0% green, 60% red, like HTML colors) + '#fcc' (100% red, 80% green, 80% blue) + 'g40' (40% gray, decimal), 'g#cc' (80% gray, hex), + '#000', 'g0', 'g#00' (black), + '#fff', 'g100', 'g#ff' (white) + 'h8' (color number 8), 'h255' (color number 255) + + None = use foreground parameter value + + background_high -- a string containing the background color, + standard background colors (see "Background colors" above) + or high-colors (see "High-color example values" above) + may be used + + None = use background parameter value + """ + basic = AttrSpec(foreground, background, 16) + + if isinstance(mono, tuple): + # old style of specifying mono attributes was to put them + # in a tuple. convert to comma-separated string + mono = ",".join(mono) + if mono is None: + mono = DEFAULT + mono_spec = AttrSpec(mono, DEFAULT, 1) + + if foreground_high is None: + foreground_high = foreground + if background_high is None: + background_high = background + + high_256 = AttrSpec(foreground_high, background_high, 256) + high_true = AttrSpec(foreground_high, background_high, 2**24) + + # 'hX' where X > 15 are different in 88/256 color, use + # basic colors for 88-color mode if high colors are specified + # in this way (also avoids crash when X > 87) + def large_h(desc: str) -> bool: + if not desc.startswith("h"): + return False + if "," in desc: + desc = desc.split(",", 1)[0] + num = int(desc[1:], 10) + return num > 15 + + if large_h(foreground_high) or large_h(background_high): + high_88 = basic + else: + high_88 = AttrSpec(foreground_high, background_high, 88) + + signals.emit_signal(self, UPDATE_PALETTE_ENTRY, name, basic, mono_spec, high_88, high_256, high_true) + self._palette[name] = (basic, mono_spec, high_88, high_256, high_true) + + +def _test(): + import doctest + + doctest.testmod() + + +if __name__ == "__main__": + _test() diff --git a/python/user_packages/Python313/site-packages/urwid/display/curses.py b/python/user_packages/Python313/site-packages/urwid/display/curses.py new file mode 100644 index 0000000000000000000000000000000000000000..6c144a64830dc1af810bbfa1555549c609a68c35 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/curses.py @@ -0,0 +1,688 @@ +# Urwid curses output wrapper.. the horror.. +# Copyright (C) 2004-2011 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Curses-based UI implementation +""" + +from __future__ import annotations + +import curses +import sys +import typing +from contextlib import suppress + +from urwid import util + +from . import escape +from .common import UNPRINTABLE_TRANS_TABLE, AttrSpec, BaseScreen, RealTerminal + +if typing.TYPE_CHECKING: + from typing_extensions import Literal + + from urwid import Canvas + +IS_WINDOWS = sys.platform == "win32" + +# curses.KEY_RESIZE (sometimes not defined) +if IS_WINDOWS: + KEY_MOUSE = 539 # under Windows key mouse is different + KEY_RESIZE = 546 + + COLOR_CORRECTION: dict[int, int] = dict( + enumerate( + ( + curses.COLOR_BLACK, + curses.COLOR_RED, + curses.COLOR_GREEN, + curses.COLOR_YELLOW, + curses.COLOR_BLUE, + curses.COLOR_MAGENTA, + curses.COLOR_CYAN, + curses.COLOR_WHITE, + ) + ) + ) + + def initscr(): + import curses # noqa: I001 # pylint: disable=redefined-outer-name,reimported # special case for monkeypatch + + import _curses + + stdscr = _curses.initscr() + for key, value in _curses.__dict__.items(): + if key[:4] == "ACS_" or key in {"LINES", "COLS"}: + setattr(curses, key, value) + + return stdscr + + curses.initscr = initscr + +else: + KEY_MOUSE = 409 # curses.KEY_MOUSE + KEY_RESIZE = 410 + + COLOR_CORRECTION = {} + +_curses_colours = { # pylint: disable=consider-using-namedtuple-or-dataclass # historic test/debug data + "default": (-1, 0), + "black": (curses.COLOR_BLACK, 0), + "dark red": (curses.COLOR_RED, 0), + "dark green": (curses.COLOR_GREEN, 0), + "brown": (curses.COLOR_YELLOW, 0), + "dark blue": (curses.COLOR_BLUE, 0), + "dark magenta": (curses.COLOR_MAGENTA, 0), + "dark cyan": (curses.COLOR_CYAN, 0), + "light gray": (curses.COLOR_WHITE, 0), + "dark gray": (curses.COLOR_BLACK, 1), + "light red": (curses.COLOR_RED, 1), + "light green": (curses.COLOR_GREEN, 1), + "yellow": (curses.COLOR_YELLOW, 1), + "light blue": (curses.COLOR_BLUE, 1), + "light magenta": (curses.COLOR_MAGENTA, 1), + "light cyan": (curses.COLOR_CYAN, 1), + "white": (curses.COLOR_WHITE, 1), +} + + +class Screen(BaseScreen, RealTerminal): + def __init__(self) -> None: + super().__init__() + self.curses_pairs = [(None, None)] # Can't be sure what pair 0 will default to + self.palette = {} + self.has_color = False + self.s = None + self.cursor_state = None + self.prev_input_resize = 0 + self.set_input_timeouts() + self.last_bstate = 0 + self._mouse_tracking_enabled = False + + self.register_palette_entry(None, "default", "default") + + def set_mouse_tracking(self, enable: bool = True) -> None: + """ + Enable mouse tracking. + + After calling this function get_input will include mouse + click events along with keystrokes. + """ + enable = bool(enable) + if enable == self._mouse_tracking_enabled: + return + + if enable: + curses.mousemask( + 0 + | curses.BUTTON1_PRESSED + | curses.BUTTON1_RELEASED + | curses.BUTTON2_PRESSED + | curses.BUTTON2_RELEASED + | curses.BUTTON3_PRESSED + | curses.BUTTON3_RELEASED + | curses.BUTTON4_PRESSED + | curses.BUTTON4_RELEASED + | curses.BUTTON1_DOUBLE_CLICKED + | curses.BUTTON1_TRIPLE_CLICKED + | curses.BUTTON2_DOUBLE_CLICKED + | curses.BUTTON2_TRIPLE_CLICKED + | curses.BUTTON3_DOUBLE_CLICKED + | curses.BUTTON3_TRIPLE_CLICKED + | curses.BUTTON4_DOUBLE_CLICKED + | curses.BUTTON4_TRIPLE_CLICKED + | curses.BUTTON_SHIFT + | curses.BUTTON_ALT + | curses.BUTTON_CTRL + ) + else: + raise NotImplementedError() + + self._mouse_tracking_enabled = enable + + def _start(self) -> None: + """ + Initialize the screen and input mode. + """ + self.s = curses.initscr() + self.has_color = curses.has_colors() + if self.has_color: + curses.start_color() + if curses.COLORS < 8: + # not colourful enough + self.has_color = False + if self.has_color: + try: + curses.use_default_colors() + self.has_default_colors = True + except curses.error: + self.has_default_colors = False + self._setup_colour_pairs() + curses.noecho() + curses.meta(True) + curses.halfdelay(10) # use set_input_timeouts to adjust + self.s.keypad(False) + + if not self._signal_keys_set: + self._old_signal_keys = self.tty_signal_keys() + + super()._start() + + if IS_WINDOWS: + # halfdelay() seems unnecessary and causes everything to slow down a lot. + curses.nocbreak() # exits halfdelay mode + # keypad(1) is needed, or we get no special keys (cursor keys, etc.) + self.s.keypad(True) + + def _stop(self) -> None: + """ + Restore the screen. + """ + curses.echo() + self._curs_set(1) + with suppress(curses.error): + curses.endwin() + # don't block original error with curses error + + if self._old_signal_keys: + self.tty_signal_keys(*self._old_signal_keys) + + super()._stop() + + def _setup_colour_pairs(self) -> None: + """ + Initialize all 63 color pairs based on the term: + bg * 8 + 7 - fg + So to get a color, we just need to use that term and get the right color + pair number. + """ + if not self.has_color: + return + + if IS_WINDOWS: + self.has_default_colors = False + + for fg in range(8): + for bg in range(8): + # leave out white on black + if fg == curses.COLOR_WHITE and bg == curses.COLOR_BLACK: + continue + + curses.init_pair(bg * 8 + 7 - fg, COLOR_CORRECTION.get(fg, fg), COLOR_CORRECTION.get(bg, bg)) + + def _curs_set(self, x: int): + if self.cursor_state in {"fixed", x}: + return + try: + curses.curs_set(x) + self.cursor_state = x + except curses.error: + self.cursor_state = "fixed" + + def _clear(self) -> None: + self.s.clear() + self.s.refresh() + + def _getch(self, wait_tenths: int | None) -> int: + if wait_tenths == 0: + return self._getch_nodelay() + + if not IS_WINDOWS: + if wait_tenths is None: + curses.cbreak() + else: + curses.halfdelay(wait_tenths) + + self.s.nodelay(False) + return self.s.getch() + + def _getch_nodelay(self) -> int: + self.s.nodelay(True) + + if not IS_WINDOWS: + while True: + # this call fails sometimes, but seems to work when I try again + with suppress(curses.error): + curses.cbreak() + break + + return self.s.getch() + + def set_input_timeouts( + self, + max_wait: float | None = None, + complete_wait: float = 0.1, + resize_wait: float = 0.1, + ): + """ + Set the get_input timeout values. All values have a granularity + of 0.1s, ie. any value between 0.15 and 0.05 will be treated as + 0.1 and any value less than 0.05 will be treated as 0. The + maximum timeout value for this module is 25.5 seconds. + + max_wait -- amount of time in seconds to wait for input when + there is no input pending, wait forever if None + complete_wait -- amount of time in seconds to wait when + get_input detects an incomplete escape sequence at the + end of the available input + resize_wait -- amount of time in seconds to wait for more input + after receiving two screen resize requests in a row to + stop urwid from consuming 100% cpu during a gradual + window resize operation + """ + + def convert_to_tenths(s): + if s is None: + return None + return int((s + 0.05) * 10) + + self.max_tenths = convert_to_tenths(max_wait) + self.complete_tenths = convert_to_tenths(complete_wait) + self.resize_tenths = convert_to_tenths(resize_wait) + + @typing.overload + def get_input(self, raw_keys: Literal[False]) -> list[str]: ... + + @typing.overload + def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... + + def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: + """Return pending input as a list. + + raw_keys -- return raw keycodes as well as translated versions + + This function will immediately return all the input since the + last time it was called. If there is no input pending it will + wait before returning an empty list. The wait time may be + configured with the set_input_timeouts function. + + If raw_keys is False (default) this function will return a list + of keys pressed. If raw_keys is True this function will return + a ( keys pressed, raw keycodes ) tuple instead. + + Examples of keys returned: + + * ASCII printable characters: " ", "a", "0", "A", "-", "/" + * ASCII control characters: "tab", "enter" + * Escape sequences: "up", "page up", "home", "insert", "f1" + * Key combinations: "shift f1", "meta a", "ctrl b" + * Window events: "window resize" + + When a narrow encoding is not enabled: + + * "Extended ASCII" characters: "\\xa1", "\\xb2", "\\xfe" + + When a wide encoding is enabled: + + * Double-byte characters: "\\xa1\\xea", "\\xb2\\xd4" + + When utf8 encoding is enabled: + + * Unicode characters: u"\\u00a5", u'\\u253c" + + Examples of mouse events returned: + + * Mouse button press: ('mouse press', 1, 15, 13), + ('meta mouse press', 2, 17, 23) + * Mouse button release: ('mouse release', 0, 18, 13), + ('ctrl mouse release', 0, 17, 23) + """ + if not self._started: + raise RuntimeError + + keys, raw = self._get_input(self.max_tenths) + + # Avoid pegging CPU at 100% when slowly resizing, and work + # around a bug with some braindead curses implementations that + # return "no key" between "window resize" commands + if keys == ["window resize"] and self.prev_input_resize: + for _ in range(2): + new_keys, new_raw = self._get_input(self.resize_tenths) + raw += new_raw + if new_keys and new_keys != ["window resize"]: + if "window resize" in new_keys: + keys = new_keys + else: + keys.extend(new_keys) + break + + if keys == ["window resize"]: + self.prev_input_resize = 2 + elif self.prev_input_resize == 2 and not keys: + self.prev_input_resize = 1 + else: + self.prev_input_resize = 0 + + if raw_keys: + return keys, raw + return keys + + def _get_input(self, wait_tenths: int | None) -> tuple[list[str], list[int]]: + # this works around a strange curses bug with window resizing + # not being reported correctly with repeated calls to this + # function without a doupdate call in between + curses.doupdate() + + key = self._getch(wait_tenths) + resize = False + raw = [] + keys = [] + + while key >= 0: + raw.append(key) + if key == KEY_RESIZE: + resize = True + elif key == KEY_MOUSE: + keys += self._encode_mouse_event() + else: + keys.append(key) + key = self._getch_nodelay() + + processed = [] + + try: + while keys: + run, keys = escape.process_keyqueue(keys, True) + processed += run + except escape.MoreInputRequired: + key = self._getch(self.complete_tenths) + while key >= 0: + raw.append(key) + if key == KEY_RESIZE: + resize = True + elif key == KEY_MOUSE: + keys += self._encode_mouse_event() + else: + keys.append(key) + key = self._getch_nodelay() + while keys: + run, keys = escape.process_keyqueue(keys, False) + processed += run + + if resize: + processed.append("window resize") + + return processed, raw + + def _encode_mouse_event(self) -> list[int]: + # convert to escape sequence + last_state = next_state = self.last_bstate + (_id, x, y, _z, bstate) = curses.getmouse() + + mod = 0 + if bstate & curses.BUTTON_SHIFT: + mod |= 4 + if bstate & curses.BUTTON_ALT: + mod |= 8 + if bstate & curses.BUTTON_CTRL: + mod |= 16 + + result = [] + + def append_button(b: int) -> None: + b |= mod + result.extend([27, ord("["), ord("M"), b + 32, x + 33, y + 33]) + + if bstate & curses.BUTTON1_PRESSED and last_state & 1 == 0: + append_button(0) + next_state |= 1 + if bstate & curses.BUTTON2_PRESSED and last_state & 2 == 0: + append_button(1) + next_state |= 2 + if bstate & curses.BUTTON3_PRESSED and last_state & 4 == 0: + append_button(2) + next_state |= 4 + if bstate & curses.BUTTON4_PRESSED and last_state & 8 == 0: + append_button(64) + next_state |= 8 + if bstate & curses.BUTTON1_RELEASED and last_state & 1: + append_button(0 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~1 + if bstate & curses.BUTTON2_RELEASED and last_state & 2: + append_button(1 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~2 + if bstate & curses.BUTTON3_RELEASED and last_state & 4: + append_button(2 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~4 + if bstate & curses.BUTTON4_RELEASED and last_state & 8: + append_button(64 + escape.MOUSE_RELEASE_FLAG) + next_state &= ~8 + + if bstate & curses.BUTTON1_DOUBLE_CLICKED: + append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + if bstate & curses.BUTTON2_DOUBLE_CLICKED: + append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + if bstate & curses.BUTTON3_DOUBLE_CLICKED: + append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + if bstate & curses.BUTTON4_DOUBLE_CLICKED: + append_button(64 + escape.MOUSE_MULTIPLE_CLICK_FLAG) + + if bstate & curses.BUTTON1_TRIPLE_CLICKED: + append_button(0 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + if bstate & curses.BUTTON2_TRIPLE_CLICKED: + append_button(1 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + if bstate & curses.BUTTON3_TRIPLE_CLICKED: + append_button(2 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + if bstate & curses.BUTTON4_TRIPLE_CLICKED: + append_button(64 + escape.MOUSE_MULTIPLE_CLICK_FLAG * 2) + + self.last_bstate = next_state + return result + + def _dbg_instr(self): # messy input string (intended for debugging) + curses.echo() + self.s.nodelay(0) + curses.halfdelay(100) + string = self.s.getstr() + curses.noecho() + return string + + def _dbg_out(self, string) -> None: # messy output function (intended for debugging) + self.s.clrtoeol() + self.s.addstr(string) + self.s.refresh() + self._curs_set(1) + + def _dbg_query(self, question): # messy query (intended for debugging) + self._dbg_out(question) + return self._dbg_instr() + + def _dbg_refresh(self) -> None: + self.s.refresh() + + def get_cols_rows(self) -> tuple[int, int]: + """Return the terminal dimensions (num columns, num rows).""" + rows, cols = self.s.getmaxyx() + return cols, rows + + def _setattr(self, a): + if a is None: + self.s.attrset(0) + return + if not isinstance(a, AttrSpec): + p = self._palette.get(a, (AttrSpec("default", "default"),)) + a = p[0] + + if self.has_color: + if a.foreground_basic: + if a.foreground_number >= 8: + fg = a.foreground_number - 8 + else: + fg = a.foreground_number + else: + fg = 7 + + if a.background_basic: + bg = a.background_number + else: + bg = 0 + + attr = curses.color_pair(bg * 8 + 7 - fg) + else: + attr = 0 + + if a.bold: + attr |= curses.A_BOLD + if a.standout: + attr |= curses.A_STANDOUT + if a.underline: + attr |= curses.A_UNDERLINE + if a.blink: + attr |= curses.A_BLINK + + self.s.attrset(attr) + + def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: + """Paint screen with rendered canvas.""" + + logger = self.logger.getChild("draw_screen") + + if not self._started: + raise RuntimeError + + _cols, rows = size + + if canvas.rows() != rows: + raise ValueError("canvas size and passed size don't match") + + logger.debug(f"Drawing screen with size {size!r}") + + for y, row in enumerate(canvas.content()): + try: + self.s.move(y, 0) + except curses.error: + # terminal shrunk? + # move failed so stop rendering. + return + + first = True + lasta = None + + for nr, (a, cs, seg) in enumerate(row): + if cs != "U": + seg = seg.translate(UNPRINTABLE_TRANS_TABLE) # noqa: PLW2901 + if not isinstance(seg, bytes): + raise TypeError(seg) + + if first or lasta != a: + self._setattr(a) + lasta = a + try: + if cs in {"0", "U"}: + for segment in seg: + self.s.addch(0x400000 + segment) + else: + if cs is not None: + raise ValueError(f"cs not in ('0', 'U' ,'None'): {cs!r}") + if not isinstance(seg, bytes): + raise TypeError(seg) + self.s.addstr(seg.decode(util.get_encoding())) + except curses.error: + # it's OK to get out of the + # screen on the lower right + if y != rows - 1 or nr != len(row) - 1: + # perhaps screen size changed + # quietly abort. + return + + if canvas.cursor is not None: + x, y = canvas.cursor + self._curs_set(1) + with suppress(curses.error): + self.s.move(y, x) + else: + self._curs_set(0) + self.s.move(0, 0) + + self.s.refresh() + self.keep_cache_alive_link = canvas + + def clear(self) -> None: + """ + Force the screen to be completely repainted on the next call to draw_screen(). + """ + self.s.clear() + + +class _test: + def __init__(self): + self.ui = Screen() + self.l = sorted(_curses_colours) + + for c in self.l: + self.ui.register_palette( + [ + (f"{c} on black", c, "black", "underline"), + (f"{c} on dark blue", c, "dark blue", "bold"), + (f"{c} on light gray", c, "light gray", "standout"), + ] + ) + + with self.ui.start(): + self.run() + + def run(self) -> None: + class FakeRender: + pass + + r = FakeRender() + text = [f" has_color = {self.ui.has_color!r}", ""] + attr = [[], []] + r.coords = {} + r.cursor = None + + for c in self.l: + t = "" + a = [] + for p in f"{c} on black", f"{c} on dark blue", f"{c} on light gray": + a.append((p, 27)) + t += (p + 27 * " ")[:27] + text.append(t) + attr.append(a) + + text += ["", "return values from get_input(): (q exits)", ""] + attr += [[], [], []] + cols, rows = self.ui.get_cols_rows() + keys = None + while keys != ["q"]: + r.text = ([t.ljust(cols) for t in text] + [""] * rows)[:rows] + r.attr = (attr + [[] for _ in range(rows)])[:rows] + self.ui.draw_screen((cols, rows), r) + keys, raw = self.ui.get_input(raw_keys=True) + if "window resize" in keys: + cols, rows = self.ui.get_cols_rows() + if not keys: + continue + t = "" + a = [] + for k in keys: + if isinstance(k, str): + k = k.encode(util.get_encoding()) # noqa: PLW2901 + + t += f"'{k}' " + a += [(None, 1), ("yellow on dark blue", len(k)), (None, 2)] + + text.append(f"{t}: {raw!r}") + attr.append(a) + text = text[-rows:] + attr = attr[-rows:] + + +if __name__ == "__main__": + _test() diff --git a/python/user_packages/Python313/site-packages/urwid/display/escape.py b/python/user_packages/Python313/site-packages/urwid/display/escape.py new file mode 100644 index 0000000000000000000000000000000000000000..11d65a14cebe9e613ca9eb28a660297081e50caa --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/escape.py @@ -0,0 +1,637 @@ +# Urwid escape sequences common to curses_display and raw_display +# Copyright (C) 2004-2011 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Terminal Escape Sequences for input and display +""" + +from __future__ import annotations + +import re +import sys +import typing +from collections.abc import MutableMapping, Sequence + +from urwid import str_util + +if typing.TYPE_CHECKING: + from collections.abc import Iterable + +# NOTE: because of circular imports (urwid.util -> urwid.escape -> urwid.util) +# from urwid.util import is_mouse_event -- will not work here +import urwid.util # isort: skip # pylint: disable=wrong-import-position + +IS_WINDOWS = sys.platform == "win32" + +within_double_byte = str_util.within_double_byte + +SO = "\x0e" +SI = "\x0f" +IBMPC_ON = "\x1b[11m" +IBMPC_OFF = "\x1b[10m" + +DEC_TAG = "0" +DEC_SPECIAL_CHARS = "▮◆▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·" +ALT_DEC_SPECIAL_CHARS = "_`abcdefghijklmnopqrstuvwxyz{|}~" + +DEC_SPECIAL_CHARMAP = {} +if len(DEC_SPECIAL_CHARS) != len(ALT_DEC_SPECIAL_CHARS): + raise RuntimeError(repr((DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS))) + +for c, alt in zip(DEC_SPECIAL_CHARS, ALT_DEC_SPECIAL_CHARS): + DEC_SPECIAL_CHARMAP[ord(c)] = SO + alt + SI + +SAFE_ASCII_DEC_SPECIAL_RE = re.compile(f"^[ -~{DEC_SPECIAL_CHARS}]*$") +DEC_SPECIAL_RE = re.compile(f"[{DEC_SPECIAL_CHARS}]") + + +################### +# Input sequences +################### + + +class MoreInputRequired(Exception): + pass + + +def escape_modifier(digit: str) -> str: + mode = ord(digit) - ord("1") + return "shift " * (mode & 1) + "meta " * ((mode & 2) // 2) + "ctrl " * ((mode & 4) // 4) + + +input_sequences = [ + ("[A", "up"), + ("[B", "down"), + ("[C", "right"), + ("[D", "left"), + ("[E", "5"), + ("[F", "end"), + ("[G", "5"), + ("[H", "home"), + ("[I", "focus in"), + ("[O", "focus out"), + ("[1~", "home"), + ("[2~", "insert"), + ("[3~", "delete"), + ("[4~", "end"), + ("[5~", "page up"), + ("[6~", "page down"), + ("[7~", "home"), + ("[8~", "end"), + ("[[A", "f1"), + ("[[B", "f2"), + ("[[C", "f3"), + ("[[D", "f4"), + ("[[E", "f5"), + ("[11~", "f1"), + ("[12~", "f2"), + ("[13~", "f3"), + ("[14~", "f4"), + ("[15~", "f5"), + ("[17~", "f6"), + ("[18~", "f7"), + ("[19~", "f8"), + ("[20~", "f9"), + ("[21~", "f10"), + ("[23~", "f11"), + ("[24~", "f12"), + ("[25~", "f13"), + ("[26~", "f14"), + ("[28~", "f15"), + ("[29~", "f16"), + ("[31~", "f17"), + ("[32~", "f18"), + ("[33~", "f19"), + ("[34~", "f20"), + ("OA", "up"), + ("OB", "down"), + ("OC", "right"), + ("OD", "left"), + ("OH", "home"), + ("OF", "end"), + ("OP", "f1"), + ("OQ", "f2"), + ("OR", "f3"), + ("OS", "f4"), + ("Oo", "/"), + ("Oj", "*"), + ("Om", "-"), + ("Ok", "+"), + ("[Z", "shift tab"), + ("On", "."), + ("[200~", "begin paste"), + ("[201~", "end paste"), + *( + (prefix + letter, modifier + key) + for prefix, modifier in zip("O[", ("meta ", "shift ")) + for letter, key in zip("abcd", ("up", "down", "right", "left")) + ), + *( + (f"[{digit}{symbol}", modifier + key) + for modifier, symbol in zip(("shift ", "meta "), "$^") + for digit, key in zip("235678", ("insert", "delete", "page up", "page down", "home", "end")) + ), + *((f"O{ord('p') + n:c}", str(n)) for n in range(10)), + *( + # modified cursor keys + home, end, 5 -- [#X and [1;#X forms + (prefix + digit + letter, escape_modifier(digit) + key) + for prefix in ("[", "[1;") + for digit in "12345678" + for letter, key in zip("ABCDEFGH", ("up", "down", "right", "left", "5", "end", "5", "home")) + ), + *( + # modified F1-F4 keys - O#X form and [1;#X form + (prefix + digit + letter, escape_modifier(digit) + f"f{number}") + for prefix in ("O", "[1;") + for digit in "12345678" + for number, letter in enumerate("PQRS", start=1) + ), + *( + # modified F1-F13 keys -- [XX;#~ form + (f"[{num!s};{digit}~", escape_modifier(digit) + key) + for digit in "12345678" + for num, key in zip( + (3, 5, 6, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 31, 32, 33, 34), + ( + "delete", + "page up", + "page down", + *(f"f{idx}" for idx in range(1, 21)), + ), + ) + ), + # mouse reporting (special handling done in KeyqueueTrie) + ("[M", "mouse"), + # mouse reporting for SGR 1006 + ("[<", "sgrmouse"), + # report status response + ("[0n", "status ok"), +] + + +class KeyqueueTrie: + __slots__ = ("data",) + + def __init__(self, sequences: Iterable[tuple[str, str]]) -> None: + self.data: dict[int, str | dict[int, str | dict[int, str]]] = {} + for s, result in sequences: + if isinstance(result, dict): + raise TypeError(result) + self.add(self.data, s, result) + + def add( + self, + root: MutableMapping[int, str | MutableMapping[int, str | MutableMapping[int, str]]], + s: str, + result: str, + ) -> None: + if not isinstance(root, MutableMapping) or not s: + raise RuntimeError("trie conflict detected") + + if ord(s[0]) in root: + self.add(root[ord(s[0])], s[1:], result) + return + if len(s) > 1: + d = {} + root[ord(s[0])] = d + self.add(d, s[1:], result) + return + root[ord(s)] = result + + def get(self, keys, more_available: bool): + if result := self.get_recurse(self.data, keys, more_available): + return result + + return self.read_cursor_position(keys, more_available) + + def get_recurse( + self, + root: ( + MutableMapping[int, str | MutableMapping[int, str | MutableMapping[int, str]]] + | typing.Literal["mouse", "sgrmouse"] + ), + keys: Sequence[int], + more_available: bool, + ): + if not isinstance(root, MutableMapping): + if root == "mouse": + return self.read_mouse_info(keys, more_available) + + if root == "sgrmouse": + return self.read_sgrmouse_info(keys, more_available) + + return (root, keys) + if not keys: + # get more keys + if more_available: + raise MoreInputRequired() + return None + if keys[0] not in root: + return None + return self.get_recurse(root[keys[0]], keys[1:], more_available) + + def read_mouse_info( + self, + keys: Sequence[int], + more_available: bool, + ) -> tuple[tuple[str, int, int, int], Sequence[int]] | None: + if len(keys) < 3: + if more_available: + raise MoreInputRequired() + return None + + b = keys[0] - 32 + x, y = (keys[1] - 33) % 256, (keys[2] - 33) % 256 # supports 0-255 + + prefixes = [] + if b & 4: + prefixes.append("shift ") + if b & 8: + prefixes.append("meta ") + if b & 16: + prefixes.append("ctrl ") + if (b & MOUSE_MULTIPLE_CLICK_MASK) >> 9 == 1: + prefixes.append("double ") + if (b & MOUSE_MULTIPLE_CLICK_MASK) >> 9 == 2: + prefixes.append("triple ") + prefix = "".join(prefixes) + + # 0->1, 1->2, 2->3, 64->4, 65->5 + button = ((b & 64) // 64 * 3) + (b & 3) + 1 + + if b & 3 == 3: + action = "release" + button = 0 + elif b & MOUSE_RELEASE_FLAG: + action = "release" + elif b & MOUSE_DRAG_FLAG: + action = "drag" + elif b & MOUSE_MULTIPLE_CLICK_MASK: + action = "click" + else: + action = "press" + + return ((f"{prefix}mouse {action}", button, x, y), keys[3:]) + + def read_sgrmouse_info( + self, + keys: Sequence[int], + more_available: bool, + ) -> tuple[tuple[str, int, int, int], Sequence[int]] | None: + # Helpful links: + # https://stackoverflow.com/questions/5966903/how-to-get-mousemove-and-mouseclick-in-bash + # http://invisible-island.net/xterm/ctlseqs/ctlseqs.pdf + + if not keys: + if more_available: + raise MoreInputRequired() + return None + + value = "" + pos_m = 0 + found_m = False + for k in keys: + value += chr(k) + if k in {ord("M"), ord("m")}: + found_m = True + break + pos_m += 1 + if not found_m: + if more_available: + raise MoreInputRequired() + return None + + (b, x, y) = (int(val) for val in value[:-1].split(";")) + action = value[-1] + # Double and triple clicks are not supported. + # They can be implemented by using a timer. + # This timer can check if the last registered click is below a certain threshold. + # This threshold is normally set in the operating system itself, + # so setting one here will cause an inconsistent behaviour. + + prefixes = [] + if b & 4: + prefixes.append("shift ") + if b & 8: + prefixes.append("meta ") + if b & 16: + prefixes.append("ctrl ") + prefix = "".join(prefixes) + + wheel_used: typing.Literal[0, 1] = (b & 64) >> 6 + + button = (wheel_used * 3) + (b & 3) + 1 + x -= 1 + y -= 1 + + if action == "M": + if b & MOUSE_DRAG_FLAG: + action = "drag" + else: + action = "press" + elif action == "m": + action = "release" + else: + raise ValueError(f"Unknown mouse action: {action!r}") + + return ((f"{prefix}mouse {action}", button, x, y), keys[pos_m + 1 :]) + + def read_cursor_position( + self, + keys: Sequence[int], + more_available: bool, + ) -> tuple[tuple[str, int, int], Sequence[int]] | None: + """ + Interpret cursor position information being sent by the + user's terminal. Returned as ('cursor position', x, y) + where (x, y) == (0, 0) is the top left of the screen. + """ + if not keys: + if more_available: + raise MoreInputRequired() + return None + if keys[0] != ord("["): + return None + # read y value + y = 0 + i = 1 + for k in keys[i:]: + i += 1 + if k == ord(";"): + if not y: + return None + break + if k < ord("0") or k > ord("9"): + return None + if not y and k == ord("0"): + return None + y = y * 10 + k - ord("0") + if not keys[i:]: + if more_available: + raise MoreInputRequired() + return None + # read x value + x = 0 + for k in keys[i:]: + i += 1 + if k == ord("R"): + if not x: + return None + return (("cursor position", x - 1, y - 1), keys[i:]) + if k < ord("0") or k > ord("9"): + return None + if not x and k == ord("0"): + return None + x = x * 10 + k - ord("0") + if not keys[i:] and more_available: + raise MoreInputRequired() + return None + + +# This is added to button value to signal mouse release by curses_display +# and raw_display when we know which button was released. NON-STANDARD +MOUSE_RELEASE_FLAG = 2048 + +# This 2-bit mask is used to check if the mouse release from curses or gpm +# is a double or triple release. 00 means single click, 01 double, +# 10 triple. NON-STANDARD +MOUSE_MULTIPLE_CLICK_MASK = 1536 + +# This is added to button value at mouse release to differentiate between +# single, double and triple press. Double release adds this times one, +# triple release adds this times two. NON-STANDARD +MOUSE_MULTIPLE_CLICK_FLAG = 512 + +# xterm adds this to the button value to signal a mouse drag event +MOUSE_DRAG_FLAG = 32 + + +################################################# +# Build the input trie from input_sequences list +input_trie = KeyqueueTrie(input_sequences) +################################################# + +_keyconv = { + -1: None, + 8: "backspace", + 9: "tab", + 10: "enter", + 13: "enter", + 127: "backspace", + # curses-only keycodes follow.. (XXX: are these used anymore?) + 258: "down", + 259: "up", + 260: "left", + 261: "right", + 262: "home", + 263: "backspace", + 265: "f1", + 266: "f2", + 267: "f3", + 268: "f4", + 269: "f5", + 270: "f6", + 271: "f7", + 272: "f8", + 273: "f9", + 274: "f10", + 275: "f11", + 276: "f12", + 277: "shift f1", + 278: "shift f2", + 279: "shift f3", + 280: "shift f4", + 281: "shift f5", + 282: "shift f6", + 283: "shift f7", + 284: "shift f8", + 285: "shift f9", + 286: "shift f10", + 287: "shift f11", + 288: "shift f12", + 330: "delete", + 331: "insert", + 338: "page down", + 339: "page up", + 343: "enter", # on numpad + 350: "5", # on numpad + 360: "end", +} + +if IS_WINDOWS: + _keyconv[351] = "shift tab" + _keyconv[358] = "end" + + +def process_keyqueue(codes: Sequence[int], more_available: bool) -> tuple[list[str], Sequence[int]]: + """ + codes -- list of key codes + more_available -- if True then raise MoreInputRequired when in the + middle of a character sequence (escape/utf8/wide) and caller + will attempt to send more key codes on the next call. + + returns (list of input, list of remaining key codes). + """ + code = codes[0] + if 32 <= code <= 126: + key = chr(code) + return [key], codes[1:] + if code in _keyconv: + return [_keyconv[code]], codes[1:] + if 0 < code < 27: + return [f"ctrl {ord('a') + code - 1:c}"], codes[1:] + if 27 < code < 32: + return [f"ctrl {ord('A') + code - 1:c}"], codes[1:] + + em = str_util.get_byte_encoding() + + if ( + em == "wide" + and code < 256 + and within_double_byte( + code.to_bytes(1, "little"), + 0, + 0, + ) + ): + if not codes[1:] and more_available: + raise MoreInputRequired() + if codes[1:] and codes[1] < 256: + db = chr(code) + chr(codes[1]) + if within_double_byte(db, 0, 1): + return [db], codes[2:] + + if em == "utf8" and 127 < code < 256: + if code & 0xE0 == 0xC0: # 2-byte form + need_more = 1 + elif code & 0xF0 == 0xE0: # 3-byte form + need_more = 2 + elif code & 0xF8 == 0xF0: # 4-byte form + need_more = 3 + else: + return [f"<{code:d}>"], codes[1:] + + for i in range(1, need_more + 1): + if len(codes) <= i: + if more_available: + raise MoreInputRequired() + + return [f"<{code:d}>"], codes[1:] + + k = codes[i] + if k > 256 or k & 0xC0 != 0x80: + return [f"<{code:d}>"], codes[1:] + + s = bytes(codes[: need_more + 1]) + + try: + return [s.decode("utf-8")], codes[need_more + 1 :] + except UnicodeDecodeError: + return [f"<{code:d}>"], codes[1:] + + if 127 < code < 256: + key = chr(code) + return [key], codes[1:] + if code != 27: + return [f"<{code:d}>"], codes[1:] + + if (result := input_trie.get(codes[1:], more_available)) is not None: + result, remaining_codes = result + return [result], remaining_codes + + if codes[1:]: + # Meta keys -- ESC+Key form + run, remaining_codes = process_keyqueue(codes[1:], more_available) + if urwid.util.is_mouse_event(run[0]): + return ["esc", *run], remaining_codes + if run[0] == "esc" or run[0].find("meta ") >= 0: + return ["esc", *run], remaining_codes + return [f"meta {run[0]}", *run[1:]], remaining_codes + + return ["esc"], codes[1:] + + +#################### +# Output sequences +#################### + +ESC = "\x1b" + +CURSOR_HOME = f"{ESC}[H" +CURSOR_HOME_COL = "\r" + +APP_KEYPAD_MODE = f"{ESC}=" +NUM_KEYPAD_MODE = f"{ESC}>" + +SWITCH_TO_ALTERNATE_BUFFER = f"{ESC}[?1049h" +RESTORE_NORMAL_BUFFER = f"{ESC}[?1049l" + +ENABLE_BRACKETED_PASTE_MODE = f"{ESC}[?2004h" +DISABLE_BRACKETED_PASTE_MODE = f"{ESC}[?2004l" + +ENABLE_FOCUS_REPORTING = f"{ESC}[?1004h" +DISABLE_FOCUS_REPORTING = f"{ESC}[?1004l" + +# RESET_SCROLL_REGION = ESC+"[;r" +# RESET = ESC+"c" + +REPORT_STATUS = f"{ESC}[5n" +REPORT_CURSOR_POSITION = f"{ESC}[6n" + +INSERT_ON = f"{ESC}[4h" +INSERT_OFF = f"{ESC}[4l" + + +def set_cursor_position(x: int, y: int) -> str: + if not isinstance(x, int): + raise TypeError(x) + if not isinstance(y, int): + raise TypeError(y) + + return ESC + f"[{y + 1:d};{x + 1:d}H" + + +def move_cursor_right(x: int) -> str: + if x < 1: + return "" + return ESC + f"[{x:d}C" + + +def move_cursor_up(x: int) -> str: + if x < 1: + return "" + return ESC + f"[{x:d}A" + + +def move_cursor_down(x: int) -> str: + if x < 1: + return "" + return ESC + f"[{x:d}B" + + +HIDE_CURSOR = f"{ESC}[?25l" +SHOW_CURSOR = f"{ESC}[?25h" + +MOUSE_TRACKING_ON = f"{ESC}[?1000h{ESC}[?1002h{ESC}[?1006h" +MOUSE_TRACKING_OFF = f"{ESC}[?1006l{ESC}[?1002l{ESC}[?1000l" + +DESIGNATE_G1_SPECIAL = f"{ESC})0" + +ERASE_IN_LINE_RIGHT = f"{ESC}[K" diff --git a/python/user_packages/Python313/site-packages/urwid/display/html_fragment.py b/python/user_packages/Python313/site-packages/urwid/display/html_fragment.py new file mode 100644 index 0000000000000000000000000000000000000000..b70a049b98a8cc1b903e4ad9483752151dc31a57 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/html_fragment.py @@ -0,0 +1,244 @@ +# Urwid html fragment output wrapper for "screen shots" +# Copyright (C) 2004-2007 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +HTML PRE-based UI implementation +""" + +from __future__ import annotations + +import html +import typing + +from urwid import str_util +from urwid.event_loop import ExitMainLoop +from urwid.util import get_encoding + +from .common import AttrSpec, BaseScreen + +if typing.TYPE_CHECKING: + from typing_extensions import Literal + + from urwid import Canvas + +# replace control characters with ?'s +_trans_table = "?" * 32 + "".join(chr(x) for x in range(32, 256)) + +_default_foreground = "black" +_default_background = "light gray" + + +class HtmlGeneratorSimulationError(Exception): + pass + + +class HtmlGenerator(BaseScreen): + # class variables + fragments: typing.ClassVar[list[str]] = [] + sizes: typing.ClassVar[list[tuple[int, int]]] = [] + keys: typing.ClassVar[list[list[str]]] = [] + started = True + + def __init__(self) -> None: + super().__init__() + self.colors = 16 + self.bright_is_bold = False # ignored + self.has_underline = True # ignored + self.register_palette_entry(None, _default_foreground, _default_background) + + def set_terminal_properties( + self, + colors: int | None = None, + bright_is_bold: bool | None = None, + has_underline: bool | None = None, + ) -> None: + if colors is None: + colors = self.colors + if bright_is_bold is None: + bright_is_bold = self.bright_is_bold + if has_underline is None: + has_underline = self.has_underline + + self.colors = colors + self.bright_is_bold = bright_is_bold + self.has_underline = has_underline + + def set_input_timeouts(self, *args: typing.Any) -> None: + pass + + def reset_default_terminal_palette(self, *args: typing.Any) -> None: + pass + + def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: + """Create an html fragment from the render object. + Append it to HtmlGenerator.fragments list. + """ + # collect output in l + lines = [] + + _cols, rows = size + + if canvas.rows() != rows: + raise ValueError(rows) + + if canvas.cursor is not None: + cx, cy = canvas.cursor + else: + cx = cy = None + + for y, row in enumerate(canvas.content()): + col = 0 + + for a, _cs, run in row: + t_run = run.decode(get_encoding()).translate(_trans_table) + if isinstance(a, AttrSpec): + aspec = a + else: + aspec = self._palette[a][{1: 1, 16: 0, 88: 2, 256: 3}[self.colors]] + + if y == cy and col <= cx: + run_width = str_util.calc_width(t_run, 0, len(t_run)) + if col + run_width > cx: + lines.append(html_span(t_run, aspec, cx - col)) + else: + lines.append(html_span(t_run, aspec)) + col += run_width + else: + lines.append(html_span(t_run, aspec)) + + lines.append("\n") + + # add the fragment to the list + self.fragments.append(f"
{''.join(lines)}
") + + def get_cols_rows(self): + """Return the next screen size in HtmlGenerator.sizes.""" + if not self.sizes: + raise HtmlGeneratorSimulationError("Ran out of screen sizes to return!") + return self.sizes.pop(0) + + @typing.overload + def get_input(self, raw_keys: Literal[False]) -> list[str]: ... + + @typing.overload + def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ... + + def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]: + """Return the next list of keypresses in HtmlGenerator.keys.""" + if not self.keys: + raise ExitMainLoop() + if raw_keys: + return (self.keys.pop(0), []) + return self.keys.pop(0) + + +_default_aspec = AttrSpec(_default_foreground, _default_background) +(_d_fg_r, _d_fg_g, _d_fg_b, _d_bg_r, _d_bg_g, _d_bg_b) = _default_aspec.get_rgb_values() + + +def html_span(s: str, aspec: AttrSpec, cursor: int = -1) -> str: + fg_r, fg_g, fg_b, bg_r, bg_g, bg_b = aspec.get_rgb_values() + # use real colours instead of default fg/bg + if fg_r is None: + fg_r, fg_g, fg_b = _d_fg_r, _d_fg_g, _d_fg_b + if bg_r is None: + bg_r, bg_g, bg_b = _d_bg_r, _d_bg_g, _d_bg_b + html_fg = f"#{fg_r:02x}{fg_g:02x}{fg_b:02x}" + html_bg = f"#{bg_r:02x}{bg_g:02x}{bg_b:02x}" + if aspec.standout: + html_fg, html_bg = html_bg, html_fg + extra = ";text-decoration:underline" * aspec.underline + ";font-weight:bold" * aspec.bold + + def _span(fg: str, bg: str, string: str) -> str: + if not s: + return "" + return f'{html.escape(string)}' + + if cursor >= 0: + c_off, _ign = str_util.calc_text_pos(s, 0, len(s), cursor) + c2_off = str_util.move_next_char(s, c_off, len(s)) + return ( + _span(html_fg, html_bg, s[:c_off]) + + _span(html_bg, html_fg, s[c_off:c2_off]) + + _span(html_fg, html_bg, s[c2_off:]) + ) + + return _span(html_fg, html_bg, s) + + +def screenshot_init(sizes: list[tuple[int, int]], keys: list[list[str]]) -> None: + """ + Replace curses_display.Screen and raw_display.Screen class with + HtmlGenerator. + + Call this function before executing an application that uses + curses_display.Screen to have that code use HtmlGenerator instead. + + sizes -- list of ( columns, rows ) tuples to be returned by each call + to HtmlGenerator.get_cols_rows() + keys -- list of lists of keys to be returned by each call to + HtmlGenerator.get_input() + + Lists of keys may include "window resize" to force the application to + call get_cols_rows and read a new screen size. + + For example, the following call will prepare an application to: + 1. start in 80x25 with its first call to get_cols_rows() + 2. take a screenshot when it calls draw_screen(..) + 3. simulate 5 "down" keys from get_input() + 4. take a screenshot when it calls draw_screen(..) + 5. simulate keys "a", "b", "c" and a "window resize" + 6. resize to 20x10 on its second call to get_cols_rows() + 7. take a screenshot when it calls draw_screen(..) + 8. simulate a "Q" keypress to quit the application + + screenshot_init( [ (80,25), (20,10) ], + [ ["down"]*5, ["a","b","c","window resize"], ["Q"] ] ) + """ + for row, col in sizes: + if not isinstance(row, int): + raise TypeError(f"sizes must be list[tuple[int, int]], with values >0 : {row!r}") + if row <= 0: + raise ValueError(f"sizes must be list[tuple[int, int]], with values >0 : {row!r}") + if not isinstance(col, int): + raise TypeError(f"sizes must be list[tuple[int, int]], with values >0 : {col!r}") + if col <= 0: + raise ValueError(f"sizes must be list[tuple[int, int]], with values >0 : {col!r}") + + for line in keys: + if not isinstance(line, list): + raise TypeError(f"keys must be list[list[str]]: {line!r}") + for k in line: + if not isinstance(k, str): + raise TypeError(f"keys must be list[list[str]]: {k!r}") + + from . import curses, raw + + curses.Screen = HtmlGenerator + raw.Screen = HtmlGenerator + + HtmlGenerator.sizes = sizes + HtmlGenerator.keys = keys + + +def screenshot_collect() -> list[str]: + """Return screenshots as a list of HTML fragments.""" + fragments, HtmlGenerator.fragments = HtmlGenerator.fragments, [] + return fragments diff --git a/python/user_packages/Python313/site-packages/urwid/display/lcd.py b/python/user_packages/Python313/site-packages/urwid/display/lcd.py new file mode 100644 index 0000000000000000000000000000000000000000..dcad9b2f288e7352e5e8759d8dc45109c7709340 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/lcd.py @@ -0,0 +1,524 @@ +# Urwid LCD display module +# Copyright (C) 2010 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +from __future__ import annotations + +import abc +import time +import typing + +from .common import BaseScreen + +if typing.TYPE_CHECKING: + from collections.abc import Iterable, Sequence + + from typing_extensions import Literal + + from urwid import Canvas + + +class LCDScreen(BaseScreen, abc.ABC): + """Base class for LCD-based screens.""" + + DISPLAY_SIZE: tuple[int, int] + + def set_terminal_properties( + self, + colors: Literal[1, 16, 88, 256, 16777216] | None = None, + bright_is_bold: bool | None = None, + has_underline: bool | None = None, + ) -> None: + pass + + def set_input_timeouts(self, *args): + pass + + def reset_default_terminal_palette(self, *args): + pass + + def get_cols_rows(self): + return self.DISPLAY_SIZE + + +class CFLCDScreen(LCDScreen, abc.ABC): + """ + Common methods for Crystal Fonts LCD displays + """ + + KEYS: typing.ClassVar[list[str | None]] = [ + None, # no key with code 0 + "up_press", + "down_press", + "left_press", + "right_press", + "enter_press", + "exit_press", + "up_release", + "down_release", + "left_release", + "right_release", + "enter_release", + "exit_release", + "ul_press", + "ur_press", + "ll_press", + "lr_press", + "ul_release", + "ur_release", + "ll_release", + "lr_release", + ] + CMD_PING = 0 + CMD_VERSION = 1 + CMD_CLEAR = 6 + CMD_CGRAM = 9 + CMD_CURSOR_POSITION = 11 # data = [col, row] + CMD_CURSOR_STYLE = 12 # data = [style (0-4)] + CMD_LCD_CONTRAST = 13 # data = [contrast (0-255)] + CMD_BACKLIGHT = 14 # data = [power (0-100)] + CMD_LCD_DATA = 31 # data = [col, row] + text + CMD_GPO = 34 # data = [pin(0-12), value(0-100)] + + # sent from device + CMD_KEY_ACTIVITY = 0x80 + CMD_ACK = 0x40 # in high two bits ie. & 0xc0 + + CURSOR_NONE = 0 + CURSOR_BLINKING_BLOCK = 1 + CURSOR_UNDERSCORE = 2 + CURSOR_BLINKING_BLOCK_UNDERSCORE = 3 + CURSOR_INVERTING_BLINKING_BLOCK = 4 + + MAX_PACKET_DATA_LENGTH = 22 + + colors = 1 + has_underline = False + + def __init__(self, device_path: str, baud: int) -> None: + """ + device_path -- eg. '/dev/ttyUSB0' + baud -- baud rate + """ + super().__init__() + self.device_path = device_path + from serial import Serial + + self._device = Serial(device_path, baud, timeout=0) + self._unprocessed = bytearray() + + @classmethod + def get_crc(cls, buf: Iterable[int]) -> bytes: + # This seed makes the output of this shift-based algorithm match + # the table-based algorithm. The center 16 bits of the 32-bit + # "newCRC" are used for the CRC. The MSB of the lower byte is used + # to see what bit was shifted out of the center 16 bit CRC + # accumulator ("carry flag analog"); + new_crc = 0x00F32100 + for byte in buf: + # Push this byte's bits through a software + # implementation of a hardware shift & xor. + for bit_count in range(8): + # Shift the CRC accumulator + new_crc >>= 1 + # The new MSB of the CRC accumulator comes + # from the LSB of the current data byte. + if byte & (0x01 << bit_count): + new_crc |= 0x00800000 + # If the low bit of the current CRC accumulator was set + # before the shift, then we need to XOR the accumulator + # with the polynomial (center 16 bits of 0x00840800) + if new_crc & 0x00000080: + new_crc ^= 0x00840800 + # All the data has been done. Do 16 more bits of 0 data. + for _bit_count in range(16): + # Shift the CRC accumulator + new_crc >>= 1 + # If the low bit of the current CRC accumulator was set + # before the shift we need to XOR the accumulator with + # 0x00840800. + if new_crc & 0x00000080: + new_crc ^= 0x00840800 + # Return the center 16 bits, making this CRC match the one's + # complement that is sent in the packet. + return (((~new_crc) >> 8) & 0xFFFF).to_bytes(2, "little") + + def _send_packet(self, command: int, data: bytes) -> None: + """ + low-level packet sending. + Following the protocol requires waiting for ack packet between + sending each packet to the device. + """ + buf = bytearray([command, len(data)]) + buf.extend(data) + buf.extend(self.get_crc(buf)) + self._device.write(buf) + + def _read_packet(self) -> tuple[int, bytearray] | None: + """ + low-level packet reading. + returns (command/report code, data) or None + + This method stored data read and tries to resync when bad data + is received. + """ + # pull in any new data available + self._unprocessed += self._device.read() + while True: + try: + command, data, unprocessed = self._parse_data(self._unprocessed) + self._unprocessed = unprocessed + except self.MoreDataRequired: # noqa: PERF203 + return None + except self.InvalidPacket: + # throw out a byte and try to parse again + self._unprocessed = self._unprocessed[1:] + else: + return command, data + + class InvalidPacket(Exception): + pass + + class MoreDataRequired(Exception): + pass + + @classmethod + def _parse_data(cls, data: bytearray) -> tuple[int, bytearray, bytearray]: + """ + Try to read a packet from the start of data, returning + (command/report code, packet_data, remaining_data) + or raising InvalidPacket or MoreDataRequired + """ + if len(data) < 2: + raise cls.MoreDataRequired + + command: int = data[0] + packet_len: int = data[1] + + if packet_len > cls.MAX_PACKET_DATA_LENGTH: + raise cls.InvalidPacket("length value too large") + + if len(data) < packet_len + 4: + raise cls.MoreDataRequired + + data_end = 2 + packet_len + if (crc := cls.get_crc(data[:data_end])) != (packet_crc := data[data_end : data_end + 2]): + raise cls.InvalidPacket(f"CRC doesn't match ({crc=}, {packet_crc=})") + + return command, data[2:data_end], data[data_end + 2 :] + + +class KeyRepeatSimulator: + """ + Provide simulated repeat key events when given press and + release events. + + If two or more keys are pressed, disable repeating until all + keys are released. + """ + + def __init__(self, repeat_delay: float, repeat_next: float) -> None: + """ + repeat_delay -- seconds to wait before starting to repeat keys + repeat_next -- time between each repeated key + """ + self.repeat_delay = repeat_delay + self.repeat_next = repeat_next + self.pressed: dict[str, float] = {} + self.multiple_pressed = False + + def press(self, key: str) -> None: + if self.pressed: + self.multiple_pressed = True + self.pressed[key] = time.time() + + def release(self, key: str) -> None: + if key not in self.pressed: + return # ignore extra release events + del self.pressed[key] + if not self.pressed: + self.multiple_pressed = False + + def next_event(self) -> tuple[float, str] | None: + """ + Return (remaining, key) where remaining is the number of seconds + (float) until the key repeat event should be sent, or None if no + events are pending. + """ + if len(self.pressed) != 1 or self.multiple_pressed: + return None + for key, val in self.pressed.items(): + return max(0.0, val + self.repeat_delay - time.time()), key + return None + + def sent_event(self) -> None: + """ + Cakk this method when you have sent a key repeat event so the + timer will be reset for the next event + """ + if len(self.pressed) != 1: + return # ignore event that shouldn't have been sent + for key in self.pressed: + self.pressed[key] = time.time() - self.repeat_delay + self.repeat_next + return + + +class CF635Screen(CFLCDScreen): + """ + Crystal Fontz 635 display + + 20x4 character display + cursor + no foreground/background colors or settings supported + + see CGROM for a list of close Unicode matches to characters available + + 6 button input + up, down, left, right, enter (check mark), exit (cross) + """ + + DISPLAY_SIZE = (20, 4) + + # ① through ⑧ are programmable CGRAM (chars 0-7, repeated at 8-15) + # double arrows (⇑⇓) appear as double arrowheads (chars 18, 19) + # ⑴ resembles a bell + # ⑵ resembles a filled-in "Y" + # ⑶ is the letters "Pt" together + # partial blocks (▇▆▄▃▁) are actually shorter versions of (▉▋▌▍▏) + # both groups are intended to draw horizontal bars with pixel + # precision, use ▇*[▆▄▃▁]? for a thin bar or ▉*[▋▌▍▏]? for a thick bar + CGROM = ( + "①②③④⑤⑥⑦⑧①②③④⑤⑥⑦⑧" + "►◄⇑⇓«»↖↗↙↘▲▼↲^ˇ█" + " !\"#¤%&'()*+,-./" + "0123456789:;<=>?" + "¡ABCDEFGHIJKLMNO" + "PQRSTUVWXYZÄÖÑܧ" + "¿abcdefghijklmno" + "pqrstuvwxyzäöñüà" + "⁰¹²³⁴⁵⁶⁷⁸⁹½¼±≥≤μ" + "♪♫⑴♥♦⑵⌜⌟“”()αɛδ∞" + "@£$¥èéùìòÇᴾØøʳÅå" + "⌂¢ΦτλΩπΨΣθΞ♈ÆæßÉ" + "ΓΛΠϒ_ÈÊêçğŞşİι~◊" + "▇▆▄▃▁ƒ▉▋▌▍▏⑶◽▪↑→" + "↓←ÁÍÓÚÝáíóúýÔôŮů" + r"ČĔŘŠŽčĕřšž[\]{|}" + ) + + cursor_style = CFLCDScreen.CURSOR_INVERTING_BLINKING_BLOCK + + def __init__( + self, + device_path: str, + baud: int = 115200, + repeat_delay: float = 0.5, + repeat_next: float = 0.125, + key_map: Iterable[str] = ("up", "down", "left", "right", "enter", "esc"), + ): + """ + device_path -- eg. '/dev/ttyUSB0' + baud -- baud rate + repeat_delay -- seconds to wait before starting to repeat keys + repeat_next -- time between each repeated key + key_map -- the keys to send for this device's buttons + """ + super().__init__(device_path, baud) + + self.repeat_delay = repeat_delay + self.repeat_next = repeat_next + self.key_repeat = KeyRepeatSimulator(repeat_delay, repeat_next) + self.key_map = tuple(key_map) + + self._last_command = None + self._last_command_time = 0 + self._command_queue: list[tuple[int, bytearray]] = [] + self._screen_buf = None + self._previous_canvas = None + self._update_cursor = False + + def get_input_descriptors(self) -> list[int]: + """ + return the fd from our serial device so we get called + on input and responses + """ + return [self._device.fd] + + def get_input_nonblocking(self) -> tuple[None, list[str], list[int]]: + """ + Return a (next_input_timeout, keys_pressed, raw_keycodes) + tuple. + + The protocol for our device requires waiting for acks between + each command, so this method responds to those as well as key + press and release events. + + Key repeat events are simulated here as the device doesn't send + any for us. + + raw_keycodes are the bytes of messages we received, which might + not seem to have any correspondence to keys_pressed. + """ + data_input: list[str] = [] + raw_data_input: list[int] = [] + timeout = None + + packet = self._read_packet() + while packet: + command, data = packet + + if command == self.CMD_KEY_ACTIVITY and data: + d0 = data[0] + if 1 <= d0 <= 12: + release = d0 > 6 + keycode = d0 - (release * 6) - 1 + key = self.key_map[keycode] + if release: + self.key_repeat.release(key) + else: + data_input.append(key) + self.key_repeat.press(key) + raw_data_input.append(d0) + + elif command & 0xC0 == 0x40 and command & 0x3F == self._last_command: # "ACK" + self._send_next_command() + + packet = self._read_packet() + + if next_repeat := self.key_repeat.next_event(): + timeout, key = next_repeat + if not timeout: + data_input.append(key) + self.key_repeat.sent_event() + timeout = None + + return timeout, data_input, raw_data_input + + def _send_next_command(self) -> None: + """ + send out the next command in the queue + """ + if not self._command_queue: + self._last_command = None + return + command, data = self._command_queue.pop(0) + self._send_packet(command, data) + self._last_command = command # record command for ACK + self._last_command_time = time.time() + + def queue_command(self, command: int, data: bytearray) -> None: + self._command_queue.append((command, data)) + # not waiting? send away! + if self._last_command is None: + self._send_next_command() + + def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None: + if size != self.DISPLAY_SIZE: + raise ValueError(size) + + if self._screen_buf: + osb = self._screen_buf + else: + osb = [] + sb = [] + + for y, row in enumerate(canvas.content()): + text = [run for _a, _cs, run in row] + + if not osb or osb[y] != text: + data = bytearray([0, y]) + for elem in text: + data.extend(elem) + self.queue_command(self.CMD_LCD_DATA, data) + sb.append(text) + + if ( + self._previous_canvas + and self._previous_canvas.cursor == canvas.cursor + and (not self._update_cursor or not canvas.cursor) + ): + pass + elif canvas.cursor is None: + self.queue_command(self.CMD_CURSOR_STYLE, bytearray([self.CURSOR_NONE])) + else: + x, y = canvas.cursor + self.queue_command(self.CMD_CURSOR_POSITION, bytearray([x, y])) + self.queue_command(self.CMD_CURSOR_STYLE, bytearray([self.cursor_style])) + + self._update_cursor = False + self._screen_buf = sb + self._previous_canvas = canvas + + def program_cgram(self, index: int, data: Sequence[int]) -> None: + """ + Program character data. + + Characters available as chr(0) through chr(7), and repeated as chr(8) through chr(15). + + index -- 0 to 7 index of character to program + + data -- list of 8, 6-bit integer values top to bottom with MSB on the left side of the character. + """ + if not 0 <= index <= 7: + raise ValueError(index) + if len(data) != 8: + raise ValueError(data) + self.queue_command(self.CMD_CGRAM, bytearray([index]) + bytearray(data)) + + def set_cursor_style(self, style: Literal[1, 2, 3, 4]) -> None: + """ + style -- CURSOR_BLINKING_BLOCK, CURSOR_UNDERSCORE, + CURSOR_BLINKING_BLOCK_UNDERSCORE or + CURSOR_INVERTING_BLINKING_BLOCK + """ + if not 1 <= style <= 4: + raise ValueError(style) + self.cursor_style = style + self._update_cursor = True + + def set_backlight(self, value: int) -> None: + """ + Set backlight brightness + + value -- 0 to 100 + """ + if not 0 <= value <= 100: + raise ValueError(value) + self.queue_command(self.CMD_BACKLIGHT, bytearray([value])) + + def set_lcd_contrast(self, value: int) -> None: + """ + value -- 0 to 255 + """ + if not 0 <= value <= 255: + raise ValueError(value) + self.queue_command(self.CMD_LCD_CONTRAST, bytearray([value])) + + def set_led_pin(self, led: Literal[0, 1, 2, 3], rg: Literal[0, 1], value: int) -> None: + """ + led -- 0 to 3 + rg -- 0 for red, 1 for green + value -- 0 to 100 + """ + if not 0 <= led <= 3: + raise ValueError(led) + if rg not in {0, 1}: + raise ValueError(rg) + if not 0 <= value <= 100: + raise ValueError(value) + self.queue_command(self.CMD_GPO, bytearray([12 - 2 * led - rg, value])) diff --git a/python/user_packages/Python313/site-packages/urwid/display/raw.py b/python/user_packages/Python313/site-packages/urwid/display/raw.py new file mode 100644 index 0000000000000000000000000000000000000000..495ac01bc5b9a131e6bd793237c51761c5d068a4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/raw.py @@ -0,0 +1,37 @@ +# Urwid raw display module +# Copyright (C) 2004-2009 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Direct terminal UI implementation +""" + +from __future__ import annotations + +import sys + +__all__ = ("Screen",) + +IS_WINDOWS = sys.platform == "win32" + +if IS_WINDOWS: + from ._win32_raw_display import Screen + +else: + from ._posix_raw_display import Screen diff --git a/python/user_packages/Python313/site-packages/urwid/display/web.py b/python/user_packages/Python313/site-packages/urwid/display/web.py new file mode 100644 index 0000000000000000000000000000000000000000..420de4a43d5d8f6a79fb897623cd8c1296e625f2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/urwid/display/web.py @@ -0,0 +1,626 @@ +# Urwid web (CGI/Asynchronous Javascript) display module +# Copyright (C) 2004-2007 Ian Ward +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# Urwid web site: https://urwid.org/ + + +""" +Urwid web application display module +""" + +from __future__ import annotations + +import dataclasses +import glob +import html +import os +import pathlib +import random +import selectors +import signal +import socket +import string +import sys +import tempfile +import typing +from contextlib import suppress + +from urwid.str_util import calc_text_pos, calc_width, move_next_char +from urwid.util import StoppingContext, get_encoding + +from .common import BaseScreen + +if typing.TYPE_CHECKING: + from typing_extensions import Literal + + from urwid import Canvas + +TEMP_DIR = tempfile.gettempdir() +CURRENT_DIR = pathlib.Path(__file__).parent + +_js_code = CURRENT_DIR.joinpath("_web.js").read_text("utf-8") + +ALARM_DELAY = 60 +POLL_CONNECT = 3 +MAX_COLS = 200 +MAX_ROWS = 100 +MAX_READ = 4096 +BUF_SZ = 16384 + +_code_colours = { + "black": "0", + "dark red": "1", + "dark green": "2", + "brown": "3", + "dark blue": "4", + "dark magenta": "5", + "dark cyan": "6", + "light gray": "7", + "dark gray": "8", + "light red": "9", + "light green": "A", + "yellow": "B", + "light blue": "C", + "light magenta": "D", + "light cyan": "E", + "white": "F", +} + +# replace control characters with ?'s +_trans_table = "?" * 32 + "".join([chr(x) for x in range(32, 256)]) + +_css_style = CURRENT_DIR.joinpath("_web.css").read_text("utf-8") + +# HTML Initial Page +_html_page = [ + """ + + +Urwid Web Display - """, + """ + + + +
+
+
The quick brown fox jumps over the lazy dog.X
+Y
+
+Urwid Web Display - """, + """ - +Status: Set up + +

+
+
+""",
+]
+
+
+class Screen(BaseScreen):
+    def __init__(self) -> None:
+        super().__init__()
+        self.palette = {}
+        self.has_color = True
+        self._started = False
+
+    @property
+    def started(self) -> bool:
+        return self._started
+
+    def register_palette(self, palette) -> None:
+        """Register a list of palette entries.
+
+        palette -- list of (name, foreground, background) or
+                   (name, same_as_other_name) palette entries.
+
+        calls self.register_palette_entry for each item in l
+        """
+
+        for item in palette:
+            if len(item) in {3, 4}:
+                self.register_palette_entry(*item)
+                continue
+            if len(item) != 2:
+                raise ValueError(f"Invalid register_palette usage: {item!r}")
+            name, like_name = item
+            if like_name not in self.palette:
+                raise KeyError(f"palette entry '{like_name}' doesn't exist")
+            self.palette[name] = self.palette[like_name]
+
+    def register_palette_entry(
+        self,
+        name: str | None,
+        foreground: str,
+        background: str,
+        mono: str | None = None,
+        foreground_high: str | None = None,
+        background_high: str | None = None,
+    ) -> None:
+        """Register a single palette entry.
+
+        name -- new entry/attribute name
+        foreground -- foreground colour
+        background -- background colour
+        mono -- monochrome terminal attribute
+
+        See curses_display.register_palette_entry for more info.
+        """
+        if foreground == "default":
+            foreground = "black"
+        if background == "default":
+            background = "light gray"
+        self.palette[name] = (foreground, background, mono)
+
+    def set_mouse_tracking(self, enable: bool = True) -> None:
+        """Not yet implemented"""
+
+    def tty_signal_keys(self, *args, **vargs):
+        """Do nothing."""
+
+    def start(self) -> StoppingContext:
+        """
+        This function reads the initial screen size, generates a
+        unique id and handles cleanup when fn exits.
+
+        web_display.set_preferences(..) must be called before calling
+        this function for the preferences to take effect
+        """
+        if self._started:
+            return StoppingContext(self)
+
+        client_init = sys.stdin.read(50)
+        if not client_init.startswith("window resize "):
+            raise ValueError(client_init)
+        _ignore1, _ignore2, x, y = client_init.split(" ", 3)
+        x = int(x)
+        y = int(y)
+        self._set_screen_size(x, y)
+        self.last_screen = {}
+        self.last_screen_width = 0
+
+        self.update_method = os.environ["HTTP_X_URWID_METHOD"]
+        if self.update_method not in {"multipart", "polling"}:
+            raise ValueError(self.update_method)
+
+        if self.update_method == "polling" and not _prefs.allow_polling:
+            sys.stdout.write("Status: 403 Forbidden\r\n\r\n")
+            sys.exit(0)
+
+        clients = glob.glob(os.path.join(_prefs.pipe_dir, "urwid*.in"))
+        if len(clients) >= _prefs.max_clients:
+            sys.stdout.write("Status: 503 Sever Busy\r\n\r\n")
+            sys.exit(0)
+
+        urwid_id = f"{random.randrange(10**9):09d}{random.randrange(10**9):09d}"  # noqa: S311
+        self.pipe_name = os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}")
+        os.mkfifo(f"{self.pipe_name}.in", 0o600)
+        signal.signal(signal.SIGTERM, self._cleanup_pipe)
+
+        self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY)
+        self.input_tail = ""
+        self.content_head = (
+            f"Content-type: multipart/x-mixed-replace;boundary=ZZ\r\nX-Urwid-ID: {urwid_id}\r\n\r\n\r\n--ZZ\r\n"
+        )
+        if self.update_method == "polling":
+            self.content_head = f"Content-type: text/plain\r\nX-Urwid-ID: {urwid_id}\r\n\r\n\r\n"
+
+        signal.signal(signal.SIGALRM, self._handle_alarm)
+        signal.alarm(ALARM_DELAY)
+        self._started = True
+
+        return StoppingContext(self)
+
+    def stop(self) -> None:
+        """
+        Restore settings and clean up.
+        """
+        if not self._started:
+            return
+
+        # XXX which exceptions does this actually raise? EnvironmentError?
+        with suppress(Exception):
+            self._close_connection()
+        signal.signal(signal.SIGTERM, signal.SIG_DFL)
+        self._cleanup_pipe()
+        self._started = False
+
+    def set_input_timeouts(self, *args: typing.Any) -> None:
+        pass
+
+    def _close_connection(self) -> None:
+        if self.update_method == "polling child":
+            self.server_socket.settimeout(0)
+            sock, _addr = self.server_socket.accept()
+            sock.sendall(b"Z")
+            sock.close()
+
+        if self.update_method == "multipart":
+            sys.stdout.write("\r\nZ\r\n--ZZ--\r\n")
+            sys.stdout.flush()
+
+    def _cleanup_pipe(self, *args) -> None:
+        if not self.pipe_name:
+            return
+        # XXX which exceptions does this actually raise? EnvironmentError?
+        with suppress(Exception):
+            os.remove(f"{self.pipe_name}.in")
+            os.remove(f"{self.pipe_name}.update")
+
+    def _set_screen_size(self, cols: int, rows: int) -> None:
+        """Set the screen size (within max size)."""
+
+        cols = min(cols, MAX_COLS)
+        rows = min(rows, MAX_ROWS)
+        self.screen_size = cols, rows
+
+    def draw_screen(self, size: tuple[int, int], canvas: Canvas) -> None:
+        """Send a screen update to the client."""
+
+        (cols, rows) = size
+
+        if cols != self.last_screen_width:
+            self.last_screen = {}
+
+        sendq = [self.content_head]
+
+        if self.update_method == "polling":
+            send = sendq.append
+        elif self.update_method == "polling child":
+            signal.alarm(0)
+            try:
+                s, _addr = self.server_socket.accept()
+            except socket.timeout:
+                sys.exit(0)
+            send = s.sendall
+        else:
+            signal.alarm(0)
+            send = sendq.append
+            send("\r\n")
+            self.content_head = ""
+
+        if canvas.rows() != rows:
+            raise ValueError(rows)
+
+        if canvas.cursor is not None:
+            cx, cy = canvas.cursor
+        else:
+            cx = cy = None
+
+        new_screen = {}
+
+        y = -1
+        for row in canvas.content():
+            y += 1
+            l_row = tuple((attr_, line.decode(get_encoding())) for attr_, _, line in row)
+
+            line = []
+
+            sig = l_row
+            if y == cy:
+                sig = (*sig, cx)
+            new_screen[sig] = [*new_screen.get(sig, []), y]
+
+            if (old_line_numbers := self.last_screen.get(sig, None)) is not None:
+                if y in old_line_numbers:
+                    old_line = y
+                else:
+                    old_line = old_line_numbers[0]
+                send(f"<{old_line:d}\n")
+                continue
+
+            col = 0
+            for a, run in l_row:
+                t_run = run.translate(_trans_table)
+                if a is None:
+                    fg, bg, _mono = "black", "light gray", None
+                else:
+                    fg, bg, _mono = self.palette[a]
+                if y == cy and col <= cx:
+                    run_width = calc_width(t_run, 0, len(t_run))
+                    if col + run_width > cx:
+                        line.append(code_span(t_run, fg, bg, cx - col))
+                    else:
+                        line.append(code_span(t_run, fg, bg))
+                    col += run_width
+                else:
+                    line.append(code_span(t_run, fg, bg))
+
+            send(f"{''.join(line)}\n")
+        self.last_screen = new_screen
+        self.last_screen_width = cols
+
+        if self.update_method == "polling":
+            sys.stdout.write("".join(sendq))
+            sys.stdout.flush()
+            sys.stdout.close()
+            self._fork_child()
+        elif self.update_method == "polling child":
+            s.close()
+        else:  # update_method == "multipart"
+            send("\r\n--ZZ\r\n")
+            sys.stdout.write("".join(sendq))
+            sys.stdout.flush()
+
+        signal.alarm(ALARM_DELAY)
+
+    def clear(self) -> None:
+        """
+        Force the screen to be completely repainted on the next
+        call to draw_screen().
+
+        (does nothing for web_display)
+        """
+
+    def _fork_child(self) -> None:
+        """
+        Fork a child to run CGI disconnected for polling update method.
+        Force parent process to exit.
+        """
+        daemonize(f"{self.pipe_name}.err")
+        self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY)
+        self.update_method = "polling child"
+        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+        s.bind(f"{self.pipe_name}.update")
+        s.listen(1)
+        s.settimeout(POLL_CONNECT)
+        self.server_socket = s
+
+    def _handle_alarm(self, sig, frame) -> None:
+        if self.update_method not in {"multipart", "polling child"}:
+            raise ValueError(self.update_method)
+        if self.update_method == "polling child":
+            # send empty update
+            try:
+                s, _addr = self.server_socket.accept()
+                s.close()
+            except socket.timeout:
+                sys.exit(0)
+        else:
+            # send empty update
+            sys.stdout.write("\r\n\r\n--ZZ\r\n")
+            sys.stdout.flush()
+        signal.alarm(ALARM_DELAY)
+
+    def get_cols_rows(self) -> tuple[int, int]:
+        """Return the screen size."""
+        return self.screen_size
+
+    @typing.overload
+    def get_input(self, raw_keys: Literal[False]) -> list[str]: ...
+
+    @typing.overload
+    def get_input(self, raw_keys: Literal[True]) -> tuple[list[str], list[int]]: ...
+
+    def get_input(self, raw_keys: bool = False) -> list[str] | tuple[list[str], list[int]]:
+        """Return pending input as a list."""
+        pending_input = []
+        resized = False
+        with selectors.DefaultSelector() as selector:
+            selector.register(self.input_fd, selectors.EVENT_READ)
+
+            iready = [event.fd for event, _ in selector.select(0.5)]
+
+        if not iready:
+            if raw_keys:
+                return [], []
+            return []
+
+        keydata = os.read(self.input_fd, MAX_READ).decode(get_encoding())
+        os.close(self.input_fd)
+        self.input_fd = os.open(f"{self.pipe_name}.in", os.O_NONBLOCK | os.O_RDONLY)
+        # sys.stderr.write( repr((keydata,self.input_tail))+"\n" )
+        keys = keydata.split("\n")
+        keys[0] = self.input_tail + keys[0]
+        self.input_tail = keys[-1]
+
+        for k in keys[:-1]:
+            if k.startswith("window resize "):
+                _ign1, _ign2, x, y = k.split(" ", 3)
+                x = int(x)
+                y = int(y)
+                self._set_screen_size(x, y)
+                resized = True
+            else:
+                pending_input.append(k)
+        if resized:
+            pending_input.append("window resize")
+
+        if raw_keys:
+            return pending_input, []
+        return pending_input
+
+
+def code_span(s: str, fg: str, bg: str, cursor: int = -1) -> str:
+    code_fg = _code_colours[fg]
+    code_bg = _code_colours[bg]
+
+    if cursor >= 0:
+        c_off, _ign = calc_text_pos(s, 0, len(s), cursor)
+        c2_off = move_next_char(s, c_off, len(s))
+
+        return (
+            code_fg
+            + code_bg
+            + s[:c_off]
+            + "\n"
+            + code_bg
+            + code_fg
+            + s[c_off:c2_off]
+            + "\n"
+            + code_fg
+            + code_bg
+            + s[c2_off:]
+            + "\n"
+        )
+
+    return f"{code_fg + code_bg + s}\n"
+
+
+def is_web_request() -> bool:
+    """
+    Return True if this is a CGI web request.
+    """
+    return "REQUEST_METHOD" in os.environ
+
+
+def handle_short_request() -> bool:
+    """
+    Handle short requests such as passing keystrokes to the application
+    or sending the initial HTML page.  If returns True, then this
+    function recognized and handled a short request, and the calling
+    script should immediately exit.
+
+    web_display.set_preferences(..) should be called before calling this
+    function for the preferences to take effect
+    """
+    if not is_web_request():
+        return False
+
+    if os.environ["REQUEST_METHOD"] == "GET":
+        # Initial request, send the HTML and javascript.
+        sys.stdout.write("Content-type: text/html\r\n\r\n" + html.escape(_prefs.app_name).join(_html_page))
+        return True
+
+    if os.environ["REQUEST_METHOD"] != "POST":
+        # Don't know what to do with head requests etc.
+        return False
+
+    if "HTTP_X_URWID_ID" not in os.environ:
+        # If no urwid id, then the application should be started.
+        return False
+
+    urwid_id = os.environ["HTTP_X_URWID_ID"]
+    if len(urwid_id) > 20:
+        # invalid. handle by ignoring
+        # assert 0, "urwid id too long!"
+        sys.stdout.write("Status: 414 URI Too Long\r\n\r\n")
+        return True
+    for c in urwid_id:
+        if c not in string.digits:
+            # invald. handle by ignoring
+            # assert 0, "invalid chars in id!"
+            sys.stdout.write("Status: 403 Forbidden\r\n\r\n")
+            return True
+
+    if os.environ.get("HTTP_X_URWID_METHOD", None) == "polling":
+        # this is a screen update request
+        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+        try:
+            s.connect(os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}.update"))
+            data = f"Content-type: text/plain\r\n\r\n{s.recv(BUF_SZ)}"
+            while data:
+                sys.stdout.write(data)
+                data = s.recv(BUF_SZ)
+        except OSError:
+            sys.stdout.write("Status: 404 Not Found\r\n\r\n")
+            return True
+        return True
+
+    # this is a keyboard input request
+    try:
+        fd = os.open((os.path.join(_prefs.pipe_dir, f"urwid{urwid_id}.in")), os.O_WRONLY)
+    except OSError:
+        sys.stdout.write("Status: 404 Not Found\r\n\r\n")
+        return True
+
+    # FIXME: use the correct encoding based on the request
+    keydata = sys.stdin.read(MAX_READ)
+    os.write(fd, keydata.encode("ascii"))
+    os.close(fd)
+    sys.stdout.write("Content-type: text/plain\r\n\r\n")
+
+    return True
+
+
+@dataclasses.dataclass
+class _Preferences:
+    app_name: str = "Unnamed Application"
+    pipe_dir: str = TEMP_DIR
+    allow_polling: bool = True
+    max_clients: int = 20
+
+
+_prefs = _Preferences()
+
+
+def set_preferences(
+    app_name: str,
+    pipe_dir: str = TEMP_DIR,
+    allow_polling: bool = True,
+    max_clients: int = 20,
+) -> None:
+    """
+    Set web_display preferences.
+
+    app_name -- application name to appear in html interface
+    pipe_dir -- directory for input pipes, daemon update sockets
+                and daemon error logs
+    allow_polling -- allow creation of daemon processes for
+                     browsers without multipart support
+    max_clients -- maximum concurrent client connections. This
+               pool is shared by all urwid applications
+               using the same pipe_dir
+    """
+    _prefs.app_name = app_name
+    _prefs.pipe_dir = pipe_dir
+    _prefs.allow_polling = allow_polling
+    _prefs.max_clients = max_clients
+
+
+class ErrorLog:
+    def __init__(self, errfile: str | pathlib.PurePath) -> None:
+        self.errfile = errfile
+
+    def write(self, err: str) -> None:
+        with open(self.errfile, "a", encoding="utf-8") as f:
+            f.write(err)
+
+
+def daemonize(errfile: str) -> None:
+    """
+    Detach process and become a daemon.
+    """
+    if os.fork():
+        os._exit(0)
+
+    os.setsid()
+    signal.signal(signal.SIGHUP, signal.SIG_IGN)
+    os.umask(0)
+
+    if os.fork():
+        os._exit(0)
+
+    os.chdir("/")
+    for fd in range(20):
+        with suppress(OSError):
+            os.close(fd)
+
+    sys.stdin = open("/dev/null", encoding="utf-8")  # noqa: SIM115  # pylint: disable=consider-using-with
+    sys.stdout = open("/dev/null", "w", encoding="utf-8")  # noqa: SIM115  # pylint: disable=consider-using-with
+    sys.stderr = ErrorLog(errfile)
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__init__.py b/python/user_packages/Python313/site-packages/urwid/event_loop/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54e674b6289e88e2cfadb3153f2203537295b7a
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/__init__.py
@@ -0,0 +1,55 @@
+"""Package with EventLoop implementations for urwid."""
+
+from __future__ import annotations
+
+import sys
+
+from .abstract_loop import EventLoop, ExitMainLoop
+from .asyncio_loop import AsyncioEventLoop
+from .main_loop import MainLoop
+from .select_loop import SelectEventLoop
+
+__all__ = (
+    "AsyncioEventLoop",
+    "EventLoop",
+    "ExitMainLoop",
+    "MainLoop",
+    "SelectEventLoop",
+)
+
+try:
+    from .twisted_loop import TwistedEventLoop
+
+    __all__ += ("TwistedEventLoop",)  # type: ignore[assignment]
+except ImportError:
+    pass
+
+try:
+    from .tornado_loop import TornadoEventLoop
+
+    __all__ += ("TornadoEventLoop",)  # type: ignore[assignment]
+except ImportError:
+    pass
+
+try:
+    from .glib_loop import GLibEventLoop
+
+    __all__ += ("GLibEventLoop",)  # type: ignore[assignment]
+except ImportError:
+    pass
+
+try:
+    from .trio_loop import TrioEventLoop
+
+    __all__ += ("TrioEventLoop",)  # type: ignore[assignment]
+except ImportError:
+    pass
+
+if sys.platform != "win32":
+    # ZMQEventLoop cause interpreter crash on windows
+    try:
+        from .zmq_loop import ZMQEventLoop
+
+        __all__ += ("ZMQEventLoop",)  # type: ignore[assignment]
+    except ImportError:
+        pass
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1219113850e0085cff937f88d5f66cc5e8b3681e
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/abstract_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/abstract_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46acb93adcb4ffa0c724552a8f80071153112786
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/abstract_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/asyncio_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/asyncio_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f01c2c5eeadba50ed9324a5c96c99a006f91c97
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/asyncio_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/glib_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/glib_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2efb26d1ed69731bd3385a4e037dba1ffcb5621f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/glib_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/main_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/main_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f13293d8b094cd4fc814dee31dc6e84811abbc7
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/main_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/select_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/select_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bccb27a048b96397740fbf646c572e118020ba5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/select_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/tornado_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/tornado_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3015ffefad77466a39171d4cfff7c40d259a894f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/tornado_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/trio_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/trio_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2f8c1f88c6d1127348886b0d6551472dc487cb4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/trio_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/twisted_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/twisted_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b142cb675ddcb3a23f95d63f0b901375d528f3c4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/twisted_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/zmq_loop.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/zmq_loop.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..304d7b790aa9c9ac0e564ea99a89bae83a0cfd1f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/event_loop/__pycache__/zmq_loop.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/abstract_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/abstract_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ba8b473b439ef77fb21d059350bac7119591a55
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/abstract_loop.py
@@ -0,0 +1,178 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Abstract shared code for urwid EventLoop implementation."""
+
+from __future__ import annotations
+
+import abc
+import logging
+import signal
+import typing
+
+if typing.TYPE_CHECKING:
+    import asyncio
+    from collections.abc import Callable
+    from concurrent.futures import Executor, Future
+    from types import FrameType
+
+    from typing_extensions import ParamSpec
+
+    _T = typing.TypeVar("_T")
+    _Spec = ParamSpec("_Spec")
+
+__all__ = ("EventLoop", "ExitMainLoop")
+
+
+class ExitMainLoop(Exception):
+    """
+    When this exception is raised within a main loop the main loop
+    will exit cleanly.
+    """
+
+
+class EventLoop(abc.ABC):
+    """
+    Abstract class representing an event loop to be used by :class:`MainLoop`.
+    """
+
+    __slots__ = ("logger",)
+
+    def __init__(self) -> None:
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> Future[_T] | asyncio.Future[_T]:
+        """Run callable in executor if supported.
+
+        :param executor: Executor to use for running the function
+        :type executor: concurrent.futures.Executor
+        :param func: function to call
+        :type func: Callable
+        :param args: arguments to function (positional only)
+        :type args: object
+        :param kwargs: keyword arguments to function (keyword only)
+        :type kwargs: object
+        :return: future object for the function call outcome.
+                 (exact future type depends on the event loop type)
+        :rtype: concurrent.futures.Future | asyncio.Future
+        """
+        raise NotImplementedError
+
+    @abc.abstractmethod
+    def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> typing.Any:
+        """
+        Call callback() a given time from now.  No parameters are
+        passed to callback.
+
+        This method has no default implementation.
+
+        Returns a handle that may be passed to remove_alarm()
+
+        seconds -- floating point time to wait before calling callback
+        callback -- function to call from event loop
+        """
+
+    @abc.abstractmethod
+    def enter_idle(self, callback):
+        """
+        Add a callback for entering idle.
+
+        This method has no default implementation.
+
+        Returns a handle that may be passed to remove_idle()
+        """
+
+    @abc.abstractmethod
+    def remove_alarm(self, handle) -> bool:
+        """
+        Remove an alarm.
+
+        This method has no default implementation.
+
+        Returns True if the alarm exists, False otherwise
+        """
+
+    @abc.abstractmethod
+    def remove_enter_idle(self, handle) -> bool:
+        """
+        Remove an idle callback.
+
+        This method has no default implementation.
+
+        Returns True if the handle was removed.
+        """
+
+    @abc.abstractmethod
+    def remove_watch_file(self, handle) -> bool:
+        """
+        Remove an input file.
+
+        This method has no default implementation.
+
+        Returns True if the input file exists, False otherwise
+        """
+
+    @abc.abstractmethod
+    def run(self) -> None:
+        """
+        Start the event loop.  Exit the loop when any callback raises
+        an exception.  If ExitMainLoop is raised, exit cleanly.
+
+        This method has no default implementation.
+        """
+
+    @abc.abstractmethod
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]):
+        """
+        Call callback() when fd has some data to read.  No parameters
+        are passed to callback.
+
+        This method has no default implementation.
+
+        Returns a handle that may be passed to remove_watch_file()
+
+        fd -- file descriptor to watch for input
+        callback -- function to call when input is available
+        """
+
+    def set_signal_handler(
+        self,
+        signum: int,
+        handler: Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers,
+    ) -> Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers | None:
+        """
+        Sets the signal handler for signal signum.
+
+        The default implementation of :meth:`set_signal_handler`
+        is simply a proxy function that calls :func:`signal.signal()`
+        and returns the resulting value.
+
+        signum -- signal number
+        handler -- function (taking signum as its single argument),
+        or `signal.SIG_IGN`, or `signal.SIG_DFL`
+        """
+        return signal.signal(signum, handler)
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/asyncio_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/asyncio_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc201cb381a2cca72414ec87f92b89fa7116760c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/asyncio_loop.py
@@ -0,0 +1,255 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Asyncio based urwid EventLoop implementation."""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import logging
+import sys
+import typing
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable
+    from concurrent.futures import Executor
+
+    from typing_extensions import ParamSpec
+
+    _Spec = ParamSpec("_Spec")
+    _T = typing.TypeVar("_T")
+
+__all__ = ("AsyncioEventLoop",)
+
+
+class AsyncioEventLoop(EventLoop):
+    """
+    Event loop based on the standard library ``asyncio`` module.
+
+    .. warning::
+        Under Windows, AsyncioEventLoop globally enforces WindowsSelectorEventLoopPolicy
+        as a side-effect of creating a class instance.
+        Original event loop policy is restored in destructor method.
+
+    .. note::
+        If you make any changes to the urwid state outside of it
+        handling input or responding to alarms (for example, from asyncio.Task
+        running in background), and wish the screen to be
+        redrawn, you must call :meth:`MainLoop.draw_screen` method of the
+        main loop manually.
+
+        A good way to do this:
+            asyncio.get_event_loop().call_soon(main_loop.draw_screen)
+    """
+
+    def __init__(self, *, loop: asyncio.AbstractEventLoop | None = None, **kwargs) -> None:
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+
+        if sys.version_info[:2] < (3, 11):
+            self._event_loop_policy_altered: bool = False
+            self._original_event_loop_policy: asyncio.AbstractEventLoopPolicy | None = None
+
+            if loop:
+                self._loop: asyncio.AbstractEventLoop = loop
+            else:
+                self._original_event_loop_policy = asyncio.get_event_loop_policy()
+                if sys.platform == "win32" and not isinstance(
+                    self._original_event_loop_policy, asyncio.WindowsSelectorEventLoopPolicy
+                ):
+                    self.logger.debug("Set WindowsSelectorEventLoopPolicy as asyncio event loop policy")
+                    asyncio.set_event_loop_policy(
+                        asyncio.WindowsSelectorEventLoopPolicy()  # pylint: disable=deprecated-class
+                    )
+                    self._event_loop_policy_altered = True
+                else:
+                    self._event_loop_policy_altered = False
+
+                self._loop = asyncio.get_event_loop()
+
+        else:
+            self._runner: asyncio.Runner | None = None
+
+            if loop:
+                self._loop: asyncio.AbstractEventLoop = loop
+            else:
+                try:
+                    self._loop = asyncio.get_running_loop()
+                except RuntimeError:
+                    self._runner = asyncio.Runner(loop_factory=asyncio.SelectorEventLoop)
+                    self._loop = self._runner.get_loop()
+
+        self._exc: BaseException | None = None
+
+        self._idle_asyncio_handle: asyncio.TimerHandle | None = None
+        self._idle_handle: int = 0
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+
+    def __del__(self) -> None:
+        if sys.version_info[:2] < (3, 11):
+            if self._event_loop_policy_altered:
+                asyncio.set_event_loop_policy(self._original_event_loop_policy)  # Restore default event loop policy
+        elif self._runner is not None:
+            self._runner.close()
+
+    def _also_call_idle(self, callback: Callable[_Spec, _T]) -> Callable[_Spec, _T]:
+        """
+        Wrap the callback to also call _entering_idle.
+        """
+
+        @functools.wraps(callback)
+        def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T:
+            if not self._idle_asyncio_handle:
+                self._idle_asyncio_handle = self._loop.call_later(0, self._entering_idle)
+            return callback(*args, **kwargs)
+
+        return wrapper
+
+    def _entering_idle(self) -> None:
+        """
+        Call all the registered idle callbacks.
+        """
+        try:
+            for callback in self._idle_callbacks.values():
+                callback()
+        finally:
+            self._idle_asyncio_handle = None
+
+    def run_in_executor(
+        self,
+        executor: Executor | None,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> asyncio.Future[_T]:
+        """Run callable in executor.
+
+        :param executor: Executor to use for running the function. Default asyncio executor is used if None.
+        :type executor: concurrent.futures.Executor | None
+        :param func: function to call
+        :type func: Callable
+        :param args: arguments to function (positional only)
+        :type args: object
+        :param kwargs: keyword arguments to function (keyword only)
+        :type kwargs: object
+        :return: future object for the function call outcome.
+        :rtype: asyncio.Future
+        """
+        return self._loop.run_in_executor(executor, functools.partial(func, *args, **kwargs))
+
+    def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> asyncio.TimerHandle:
+        """
+        Call callback() a given time from now.  No parameters are
+        passed to callback.
+
+        Returns a handle that may be passed to remove_alarm()
+
+        seconds -- time in seconds to wait before calling callback
+        callback -- function to call from event loop
+        """
+        return self._loop.call_later(seconds, self._also_call_idle(callback))
+
+    def remove_alarm(self, handle) -> bool:
+        """
+        Remove an alarm.
+
+        Returns True if the alarm exists, False otherwise
+        """
+        existed = not handle.cancelled()
+        handle.cancel()
+        return existed
+
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int:
+        """
+        Call callback() when fd has some data to read.  No parameters
+        are passed to callback.
+
+        Returns a handle that may be passed to remove_watch_file()
+
+        fd -- file descriptor to watch for input
+        callback -- function to call when input is available
+        """
+        self._loop.add_reader(fd, self._also_call_idle(callback))
+        return fd
+
+    def remove_watch_file(self, handle: int) -> bool:
+        """
+        Remove an input file.
+
+        Returns True if the input file exists, False otherwise
+        """
+        return self._loop.remove_reader(handle)
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a callback for entering idle.
+
+        Returns a handle that may be passed to remove_enter_idle()
+        """
+        # XXX there's no such thing as "idle" in most event loops; this fakes
+        # it by adding extra callback to the timer and file watch callbacks.
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """
+        Remove an idle callback.
+
+        Returns True if the handle was removed.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def _exception_handler(self, loop: asyncio.AbstractEventLoop, context):
+        if exc := context.get("exception"):
+            loop.stop()
+
+            if self._idle_asyncio_handle:
+                # clean it up to prevent old callbacks
+                # from messing things up if loop is restarted
+                self._idle_asyncio_handle.cancel()
+                self._idle_asyncio_handle = None
+
+            if not isinstance(exc, ExitMainLoop):
+                # Store the exc_info so we can re-raise after the loop stops
+                self._exc = exc
+        else:
+            loop.default_exception_handler(context)
+
+    def run(self) -> None:
+        """Start the event loop.
+
+        Exit the loop when any callback raises an exception.
+        If ExitMainLoop is raised, exit cleanly.
+        """
+        self._loop.set_exception_handler(self._exception_handler)
+        self._loop.run_forever()
+        if self._exc:
+            exc = self._exc
+            self._exc = None
+            raise exc.with_traceback(exc.__traceback__)
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/glib_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/glib_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e3f493d75f74b7bebd2fcc82b4ed8b9d4f5f39
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/glib_loop.py
@@ -0,0 +1,294 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""GLib based urwid EventLoop implementation.
+
+PyGObject library is required.
+"""
+
+from __future__ import annotations
+
+import functools
+import logging
+import signal
+import typing
+
+from gi.repository import GLib
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable
+    from concurrent.futures import Executor, Future
+    from types import FrameType
+
+    from typing_extensions import Literal, ParamSpec
+
+    _Spec = ParamSpec("_Spec")
+    _T = typing.TypeVar("_T")
+
+__all__ = ("GLibEventLoop",)
+
+
+def _ignore_handler(_sig: int, _frame: FrameType | None = None) -> None:
+    return None
+
+
+class GLibEventLoop(EventLoop):
+    """
+    Event loop based on GLib.MainLoop
+    """
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        self._alarms: list[int] = []
+        self._watch_files: dict[int, int] = {}
+        self._idle_handle: int = 0
+        self._glib_idle_enabled = False  # have we called glib.idle_add?
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+        self._loop = GLib.MainLoop()
+        self._exc: BaseException | None = None
+        self._enable_glib_idle()
+        self._signal_handlers: dict[int, int] = {}
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> Future[_T]:
+        """Run callable in executor.
+
+        :param executor: Executor to use for running the function
+        :type executor: concurrent.futures.Executor
+        :param func: function to call
+        :type func: Callable
+        :param args: positional arguments to function
+        :type args: object
+        :param kwargs: keyword arguments to function
+        :type kwargs: object
+        :return: future object for the function call outcome.
+        :rtype: concurrent.futures.Future
+        """
+        return executor.submit(func, *args, **kwargs)
+
+    def alarm(
+        self,
+        seconds: float,
+        callback: Callable[[], typing.Any],
+    ) -> tuple[int, Callable[[], typing.Any]]:
+        """
+        Call callback() a given time from now.  No parameters are
+        passed to callback.
+
+        Returns a handle that may be passed to remove_alarm()
+
+        seconds -- floating point time to wait before calling callback
+        callback -- function to call from event loop
+        """
+
+        @self.handle_exit
+        def ret_false() -> Literal[False]:
+            callback()
+            self._enable_glib_idle()
+            return False
+
+        fd = GLib.timeout_add(int(seconds * 1000), ret_false)
+        self._alarms.append(fd)
+        return (fd, callback)
+
+    def set_signal_handler(
+        self,
+        signum: int,
+        handler: Callable[[int, FrameType | None], typing.Any] | int | signal.Handlers,
+    ) -> None:
+        """
+        Sets the signal handler for signal signum.
+
+        .. WARNING::
+            Because this method uses the `GLib`-specific `unix_signal_add`
+            function, its behaviour is different than `signal.signal().`
+
+            If `signum` is not `SIGHUP`, `SIGINT`, `SIGTERM`, `SIGUSR1`,
+            `SIGUSR2` or `SIGWINCH`, this method performs no actions and
+            immediately returns None.
+
+            Returns None in all cases (unlike :func:`signal.signal()`).
+        ..
+
+        signum -- signal number
+        handler -- function (taking signum as its single argument),
+        or `signal.SIG_IGN`, or `signal.SIG_DFL`
+        """
+        glib_signals = [
+            signal.SIGHUP,
+            signal.SIGINT,
+            signal.SIGTERM,
+            signal.SIGUSR1,
+            signal.SIGUSR2,
+        ]
+
+        # GLib supports SIGWINCH as of version 2.54.
+        if not GLib.check_version(2, 54, 0):
+            glib_signals.append(signal.SIGWINCH)
+
+        if signum not in glib_signals:
+            # The GLib event loop supports only the signals listed above
+            return
+
+        if signum in self._signal_handlers:
+            GLib.source_remove(self._signal_handlers.pop(signum))
+
+        if handler == signal.Handlers.SIG_IGN:
+            handler = _ignore_handler
+        elif handler == signal.Handlers.SIG_DFL:
+            return
+
+        def final_handler(signal_number: int):
+            # MyPy False-negative: signal.Handlers casted
+            handler(signal_number, None)  # type: ignore[operator]
+            return GLib.SOURCE_CONTINUE
+
+        source = GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signum, final_handler, signum)
+        self._signal_handlers[signum] = source
+
+    def remove_alarm(self, handle) -> bool:
+        """
+        Remove an alarm.
+
+        Returns True if the alarm exists, False otherwise
+        """
+        try:
+            self._alarms.remove(handle[0])
+            GLib.source_remove(handle[0])
+
+        except ValueError:
+            return False
+
+        return True
+
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int:
+        """
+        Call callback() when fd has some data to read.  No parameters
+        are passed to callback.
+
+        Returns a handle that may be passed to remove_watch_file()
+
+        fd -- file descriptor to watch for input
+        callback -- function to call when input is available
+        """
+
+        @self.handle_exit
+        def io_callback(source, cb_condition) -> Literal[True]:
+            callback()
+            self._enable_glib_idle()
+            return True
+
+        self._watch_files[fd] = GLib.io_add_watch(fd, GLib.IO_IN, io_callback)
+        return fd
+
+    def remove_watch_file(self, handle: int) -> bool:
+        """
+        Remove an input file.
+
+        Returns True if the input file exists, False otherwise
+        """
+        if handle in self._watch_files:
+            GLib.source_remove(self._watch_files[handle])
+            del self._watch_files[handle]
+            return True
+        return False
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a callback for entering idle.
+
+        Returns a handle that may be passed to remove_enter_idle()
+        """
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def _enable_glib_idle(self) -> None:
+        if self._glib_idle_enabled:
+            return
+        GLib.idle_add(self._glib_idle_callback)
+        self._glib_idle_enabled = True
+
+    def _glib_idle_callback(self):
+        for callback in self._idle_callbacks.values():
+            callback()
+        self._glib_idle_enabled = False
+        return False  # ask glib not to call again (or we would be called
+
+    def remove_enter_idle(self, handle) -> bool:
+        """
+        Remove an idle callback.
+
+        Returns True if the handle was removed.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def run(self) -> None:
+        """
+        Start the event loop.  Exit the loop when any callback raises
+        an exception.  If ExitMainLoop is raised, exit cleanly.
+        """
+        try:
+            self._loop.run()
+        finally:
+            if self._loop.is_running():
+                self._loop.quit()
+        if self._exc:
+            # An exception caused us to exit, raise it now
+            exc = self._exc
+            self._exc = None
+            raise exc.with_traceback(exc.__traceback__)
+
+    def handle_exit(self, f: Callable[_Spec, _T]) -> Callable[_Spec, _T | Literal[False]]:
+        """
+        Decorator that cleanly exits the :class:`GLibEventLoop` if
+        :exc:`ExitMainLoop` is thrown inside of the wrapped function. Store the
+        exception info if some other exception occurs, it will be reraised after
+        the loop quits.
+
+        *f* -- function to be wrapped
+        """
+
+        @functools.wraps(f)
+        def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | Literal[False]:
+            try:
+                return f(*args, **kwargs)
+            except ExitMainLoop:
+                self._loop.quit()
+            except BaseException as exc:
+                self._exc = exc
+                if self._loop.is_running():
+                    self._loop.quit()
+            return False
+
+        return wrapper
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/main_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/main_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..27c9ee89cfd69f9495078b42a8fad0d9a69c31fb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/main_loop.py
@@ -0,0 +1,716 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+from __future__ import annotations
+
+import heapq
+import logging
+import os
+import sys
+import time
+import typing
+import warnings
+from contextlib import suppress
+
+from urwid import display, signals
+from urwid.command_map import Command, command_map
+from urwid.display.common import INPUT_DESCRIPTORS_CHANGED
+from urwid.util import StoppingContext, is_mouse_event
+from urwid.widget import PopUpTarget
+
+from .abstract_loop import ExitMainLoop
+from .select_loop import SelectEventLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Iterable
+
+    from typing_extensions import Self
+
+    from urwid.display import BaseScreen
+    from urwid.widget import Widget
+
+    from .abstract_loop import EventLoop
+
+    _T = typing.TypeVar("_T")
+
+
+IS_WINDOWS = sys.platform == "win32"
+PIPE_BUFFER_READ_SIZE = 4096  # can expect this much on Linux, so try for that
+
+__all__ = ("CantUseExternalLoop", "MainLoop")
+
+
+class CantUseExternalLoop(Exception):
+    pass
+
+
+class MainLoop:
+    """
+    This is the standard main loop implementation for a single interactive
+    session.
+
+    :param widget: the topmost widget used for painting the screen, stored as
+                   :attr:`widget` and may be modified. Must be a box widget.
+    :type widget: widget instance
+
+    :param palette: initial palette for screen
+    :type palette: iterable of palette entries
+
+    :param screen: screen to use, default is a new :class:`raw_display.Screen`
+                   instance; stored as :attr:`screen`
+    :type screen: display module screen instance
+
+    :param handle_mouse: ``True`` to ask :attr:`.screen` to process mouse events
+    :type handle_mouse: bool
+
+    :param input_filter: a function to filter input before sending it to
+                   :attr:`.widget`, called from :meth:`.input_filter`
+    :type input_filter: callable
+
+    :param unhandled_input: a function called when input is not handled by
+                            :attr:`.widget`, called from :meth:`.unhandled_input`
+    :type unhandled_input: callable
+
+    :param event_loop: if :attr:`.screen` supports external an event loop it may be
+                       given here, default is a new :class:`SelectEventLoop` instance;
+                       stored as :attr:`.event_loop`
+    :type event_loop: event loop instance
+
+    :param pop_ups: `True` to wrap :attr:`.widget` with a :class:`PopUpTarget`
+                    instance to allow any widget to open a pop-up anywhere on the screen
+    :type pop_ups: boolean
+
+
+    .. attribute:: screen
+
+        The screen object this main loop uses for screen updates and reading input
+
+    .. attribute:: event_loop
+
+        The event loop object this main loop uses for waiting on alarms and IO
+    """
+
+    def __init__(
+        self,
+        widget: Widget,
+        palette: Iterable[
+            tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] | tuple[str, str, str, str, str, str]
+        ] = (),
+        screen: BaseScreen | None = None,
+        handle_mouse: bool = True,
+        input_filter: Callable[[list[str], list[int]], list[str]] | None = None,
+        unhandled_input: Callable[[str | tuple[str, int, int, int]], bool | None] | None = None,
+        event_loop: EventLoop | None = None,
+        pop_ups: bool = False,
+    ):
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        self._widget = widget
+        self.handle_mouse = handle_mouse
+        self._pop_ups = False  # only initialize placeholder
+        self.pop_ups = pop_ups  # triggers property setting side-effect
+
+        if not screen:
+            screen = display.raw.Screen()
+
+        if palette:
+            screen.register_palette(palette)
+
+        self.screen: BaseScreen = screen
+        self.screen_size: tuple[int, int] | None = None
+
+        self._unhandled_input = unhandled_input
+        self._input_filter = input_filter
+
+        if not hasattr(screen, "hook_event_loop") and event_loop is not None:
+            raise NotImplementedError(f"screen object passed {screen!r} does not support external event loops")
+        if event_loop is None:
+            event_loop = SelectEventLoop()
+        self.event_loop: EventLoop = event_loop
+
+        if hasattr(self.screen, "signal_handler_setter"):
+            # Tell the screen what function it must use to set
+            # signal handlers
+            self.screen.signal_handler_setter = self.event_loop.set_signal_handler
+
+        self._watch_pipes: dict[int, tuple[Callable[[], typing.Any], int]] = {}
+
+    @property
+    def widget(self) -> Widget:
+        """
+        Property for the topmost widget used to draw the screen.
+        This must be a box widget.
+        """
+        return self._widget
+
+    @widget.setter
+    def widget(self, widget: Widget) -> None:
+        self._widget = widget
+        if self.pop_ups:
+            self._topmost_widget.original_widget = self._widget
+        else:
+            self._topmost_widget = self._widget
+
+    def _set_widget(self, widget: Widget) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}._set_widget` is deprecated, "
+            f"please use `{self.__class__.__name__}.widget` property."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.widget = widget
+
+    @property
+    def pop_ups(self) -> bool:
+        return self._pop_ups
+
+    @pop_ups.setter
+    def pop_ups(self, pop_ups: bool) -> None:
+        self._pop_ups = pop_ups
+        if pop_ups:
+            self._topmost_widget = PopUpTarget(self._widget)
+        else:
+            self._topmost_widget = self._widget
+
+    def _set_pop_ups(self, pop_ups: bool) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}._set_pop_ups` is deprecated, "
+            f"please use `{self.__class__.__name__}.pop_ups` property."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.pop_ups = pop_ups
+
+    def set_alarm_in(self, sec: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None):
+        """
+        Schedule an alarm in *sec* seconds that will call *callback* from the
+        within the :meth:`run` method.
+
+        :param sec: seconds until alarm
+        :type sec: float
+        :param callback: function to call with two parameters: this main loop
+                         object and *user_data*
+        :type callback: callable
+        :param user_data: optional user data to pass to the callback
+        :type user_data: object
+        """
+        self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}")
+
+        def cb() -> None:
+            callback(self, user_data)
+
+        return self.event_loop.alarm(sec, cb)
+
+    def set_alarm_at(self, tm: float, callback: Callable[[Self, _T], typing.Any], user_data: _T = None):
+        """
+        Schedule an alarm at *tm* time that will call *callback* from the
+        within the :meth:`run` function. Returns a handle that may be passed to
+        :meth:`remove_alarm`.
+
+        :param tm: time to call callback e.g. ``time.time() + 5``
+        :type tm: float
+        :param callback: function to call with two parameters: this main loop
+                         object and *user_data*
+        :type callback: callable
+        :param user_data: optional user data to pass to the callback
+        :type user_data: object
+        """
+        sec = tm - time.time()
+        self.logger.debug(f"Setting alarm in {sec!r} seconds with callback {callback!r}")
+
+        def cb() -> None:
+            callback(self, user_data)
+
+        return self.event_loop.alarm(sec, cb)
+
+    def remove_alarm(self, handle) -> bool:
+        """
+        Remove an alarm. Return ``True`` if *handle* was found, ``False``
+        otherwise.
+        """
+        return self.event_loop.remove_alarm(handle)
+
+    if not IS_WINDOWS:
+
+        def watch_pipe(self, callback: Callable[[bytes], bool | None]) -> int:
+            """
+            Create a pipe for use by a subprocess or thread to trigger a callback
+            in the process/thread running the main loop.
+
+            :param callback: function taking one parameter to call from within the process/thread running the main loop
+            :type callback: callable
+
+            This method returns a file descriptor attached to the write end of a pipe.
+            The read end of the pipe is added to the list of files :attr:`event_loop` is watching.
+            When data is written to the pipe the callback function will be called
+            and passed a single value containing data read from the pipe.
+
+            This method may be used any time you want to update widgets from another thread or subprocess.
+
+            Data may be written to the returned file descriptor with ``os.write(fd, data)``.
+            Ensure that data is less than 512 bytes (or 4K on Linux)
+            so that the callback will be triggered just once with the complete value of data passed in.
+
+            If the callback returns ``False`` then the watch will be removed from :attr:`event_loop`
+            and the read end of the pipe will be closed.
+            You are responsible for closing the write end of the pipe with ``os.close(fd)``.
+            """
+            import fcntl
+
+            pipe_rd, pipe_wr = os.pipe()
+            fcntl.fcntl(pipe_rd, fcntl.F_SETFL, os.O_NONBLOCK)
+            watch_handle = None
+
+            def cb() -> None:
+                data = os.read(pipe_rd, PIPE_BUFFER_READ_SIZE)
+                if callback(data) is False:
+                    self.event_loop.remove_watch_file(watch_handle)
+                    os.close(pipe_rd)
+
+            watch_handle = self.event_loop.watch_file(pipe_rd, cb)
+            self._watch_pipes[pipe_wr] = (watch_handle, pipe_rd)
+            return pipe_wr
+
+        def remove_watch_pipe(self, write_fd: int) -> bool:
+            """
+            Close the read end of the pipe and remove the watch created by :meth:`watch_pipe`.
+
+            ..note:: You are responsible for closing the write end of the pipe.
+
+            Returns ``True`` if the watch pipe exists, ``False`` otherwise
+            """
+            try:
+                watch_handle, pipe_rd = self._watch_pipes.pop(write_fd)
+            except KeyError:
+                return False
+
+            if not self.event_loop.remove_watch_file(watch_handle):
+                return False
+            os.close(pipe_rd)
+            return True
+
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]):
+        """
+        Call *callback* when *fd* has some data to read. No parameters are
+        passed to callback.
+
+        Returns a handle that may be passed to :meth:`remove_watch_file`.
+        """
+        self.logger.debug(f"Setting watch file descriptor {fd!r} with {callback!r}")
+        return self.event_loop.watch_file(fd, callback)
+
+    def remove_watch_file(self, handle):
+        """
+        Remove a watch file. Returns ``True`` if the watch file
+        exists, ``False`` otherwise.
+        """
+        return self.event_loop.remove_watch_file(handle)
+
+    def run(self) -> None:
+        """
+        Start the main loop handling input events and updating the screen. The
+        loop will continue until an :exc:`ExitMainLoop` exception is raised.
+
+        If you would prefer to manage the event loop yourself, don't use this
+        method.  Instead, call :meth:`start` before starting the event loop,
+        and :meth:`stop` once it's finished.
+        """
+        with suppress(ExitMainLoop):
+            self._run()
+
+    def _test_run(self):
+        """
+        >>> w = _refl("widget")  # _refl prints out function calls
+        >>> w.render_rval = "fake canvas"  # *_rval is used for return values
+        >>> scr = _refl("screen")
+        >>> scr.get_input_descriptors_rval = [42]
+        >>> scr.get_cols_rows_rval = (20, 10)
+        >>> scr.started = True
+        >>> scr._urwid_signals = {}
+        >>> evl = _refl("event_loop")
+        >>> evl.enter_idle_rval = 1
+        >>> evl.watch_file_rval = 2
+        >>> ml = MainLoop(w, [], scr, event_loop=evl)
+        >>> ml.run()  # doctest:+ELLIPSIS
+        screen.start()
+        screen.set_mouse_tracking()
+        screen.unhook_event_loop(...)
+        screen.hook_event_loop(...)
+        event_loop.enter_idle()
+        event_loop.run()
+        event_loop.remove_enter_idle(1)
+        screen.unhook_event_loop(...)
+        screen.stop()
+        >>> ml.draw_screen()  # doctest:+ELLIPSIS
+        screen.get_cols_rows()
+        widget.render((20, 10), focus=True)
+        screen.draw_screen((20, 10), 'fake canvas')
+        """
+
+    def start(self) -> StoppingContext:
+        """
+        Sets up the main loop, hooking into the event loop where necessary.
+        Starts the :attr:`screen` if it hasn't already been started.
+
+        If you want to control starting and stopping the event loop yourself,
+        you should call this method before starting, and call `stop` once the
+        loop has finished.  You may also use this method as a context manager,
+        which will stop the loop automatically at the end of the block:
+
+            with main_loop.start():
+                ...
+
+        Note that some event loop implementations don't handle exceptions
+        specially if you manage the event loop yourself.  In particular, the
+        Twisted and asyncio loops won't stop automatically when
+        :exc:`ExitMainLoop` (or anything else) is raised.
+        """
+
+        self.logger.debug(f"Starting event loop {self.event_loop.__class__.__name__!r} to manage display.")
+
+        self.screen.start()
+
+        if self.handle_mouse:
+            self.screen.set_mouse_tracking()
+
+        if not hasattr(self.screen, "hook_event_loop"):
+            raise CantUseExternalLoop(f"Screen {self.screen!r} doesn't support external event loops")
+
+        with suppress(NameError):
+            signals.connect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors)
+
+        # watch our input descriptors
+        self._reset_input_descriptors()
+        self.idle_handle = self.event_loop.enter_idle(self.entering_idle)
+
+        # the screen is redrawn automatically after input and alarms,
+        # however, there can be none of those at the start,
+        # so draw the initial screen here unconditionally
+        self.event_loop.alarm(0, self.entering_idle)
+
+        return StoppingContext(self)
+
+    def stop(self) -> None:
+        """
+        Cleans up any hooks added to the event loop.  Only call this if you're
+        managing the event loop yourself, after the loop stops.
+        """
+
+        self.event_loop.remove_enter_idle(self.idle_handle)
+        del self.idle_handle
+        signals.disconnect_signal(self.screen, INPUT_DESCRIPTORS_CHANGED, self._reset_input_descriptors)
+        self.screen.unhook_event_loop(self.event_loop)
+
+        self.screen.stop()
+
+    def _reset_input_descriptors(self) -> None:
+        self.screen.unhook_event_loop(self.event_loop)
+        self.screen.hook_event_loop(self.event_loop, self._update)
+
+    def _run(self) -> None:
+        try:
+            self.start()
+        except CantUseExternalLoop:
+            try:
+                self._run_screen_event_loop()
+                return
+            finally:
+                self.screen.stop()
+
+        try:
+            self.event_loop.run()
+        except:
+            self.screen.stop()  # clean up screen control
+            raise
+        self.stop()
+
+    def _update(self, keys: list[str], raw: list[int]) -> None:
+        """
+        >>> w = _refl("widget")
+        >>> w.selectable_rval = True
+        >>> w.mouse_event_rval = True
+        >>> scr = _refl("screen")
+        >>> scr.get_cols_rows_rval = (15, 5)
+        >>> evl = _refl("event_loop")
+        >>> ml = MainLoop(w, [], scr, event_loop=evl)
+        >>> ml._input_timeout = "old timeout"
+        >>> ml._update(["y"], [121])  # doctest:+ELLIPSIS
+        screen.get_cols_rows()
+        widget.selectable()
+        widget.keypress((15, 5), 'y')
+        >>> ml._update([("mouse press", 1, 5, 4)], [])
+        widget.mouse_event((15, 5), 'mouse press', 1, 5, 4, focus=True)
+        >>> ml._update([], [])
+        """
+        if keys := self.input_filter(keys, raw):
+            self.process_input(keys)
+            if "window resize" in keys:
+                self.screen_size = None
+
+    def _run_screen_event_loop(self) -> None:
+        """
+        This method is used when the screen does not support using external event loops.
+
+        The alarms stored in the SelectEventLoop in :attr:`event_loop` are modified by this method.
+        """
+        # pylint: disable=protected-access  # special case for alarms handling
+        self.logger.debug(f"Starting screen {self.screen!r} event loop")
+
+        next_alarm = None
+
+        while True:
+            self.draw_screen()
+
+            if not next_alarm and self.event_loop._alarms:
+                next_alarm = heapq.heappop(self.event_loop._alarms)
+
+            keys: list[str] = []
+            raw: list[int] = []
+            while not keys:
+                if next_alarm:
+                    sec = max(0.0, next_alarm[0] - time.time())
+                    self.screen.set_input_timeouts(sec)
+                else:
+                    self.screen.set_input_timeouts(None)
+                keys, raw = self.screen.get_input(True)
+                if not keys and next_alarm and next_alarm[0] - time.time() <= 0:
+                    break
+
+            if keys := self.input_filter(keys, raw):
+                self.process_input(keys)
+
+            while next_alarm:
+                if (next_alarm[0] - time.time()) > 0:
+                    break
+                _tm, _tie_break, callback = next_alarm
+                callback()
+
+                if self.event_loop._alarms:
+                    next_alarm = heapq.heappop(self.event_loop._alarms)
+                else:
+                    next_alarm = None
+
+            if "window resize" in keys:
+                self.screen_size = None
+
+    def _test_run_screen_event_loop(self):
+        """
+        >>> w = _refl("widget")
+        >>> scr = _refl("screen")
+        >>> scr.get_cols_rows_rval = (10, 5)
+        >>> scr.get_input_rval = [], []
+        >>> ml = MainLoop(w, screen=scr)
+        >>> def stop_now(loop, data):
+        ...     raise ExitMainLoop()
+        >>> handle = ml.set_alarm_in(0, stop_now)
+        >>> try:
+        ...     ml._run_screen_event_loop()
+        ... except ExitMainLoop:
+        ...     pass
+        screen.get_cols_rows()
+        widget.render((10, 5), focus=True)
+        screen.draw_screen((10, 5), None)
+        screen.set_input_timeouts(0.0)
+        screen.get_input(True)
+        """
+
+    def process_input(self, keys: Iterable[str | tuple[str, int, int, int]]) -> bool:
+        """
+        This method will pass keyboard input and mouse events to :attr:`widget`.
+        This method is called automatically from the :meth:`run` method when
+        there is input, but may also be called to simulate input from the user.
+
+        *keys* is a list of input returned from :attr:`screen`'s get_input()
+        or get_input_nonblocking() methods.
+
+        Returns ``True`` if any key was handled by a widget or the
+        :meth:`unhandled_input` method.
+        """
+        self.logger.debug(f"Processing input: keys={keys!r}")
+        if not self.screen_size:
+            self.screen_size = self.screen.get_cols_rows()
+
+        something_handled = False
+
+        for key in keys:
+            if key == "window resize":
+                continue
+
+            if isinstance(key, str):
+                if self._topmost_widget.selectable():
+                    if handled_key := self._topmost_widget.keypress(self.screen_size, key):
+                        key = handled_key  # noqa: PLW2901
+
+                    else:
+                        something_handled = True
+                        continue
+
+            elif is_mouse_event(key):
+                event, button, col, row = key
+                if hasattr(self._topmost_widget, "mouse_event") and self._topmost_widget.mouse_event(
+                    self.screen_size,
+                    event,
+                    button,
+                    col,
+                    row,
+                    focus=True,
+                ):
+                    something_handled = True
+                    continue
+
+            else:
+                raise TypeError(f"{key!r} is not str | tuple[str, int, int, int]")
+
+            if key:
+                if command_map[key] == Command.REDRAW_SCREEN:
+                    self.screen.clear()
+                    something_handled = True
+                else:
+                    something_handled |= bool(self.unhandled_input(key))
+            else:
+                something_handled = True
+
+        return something_handled
+
+    def _test_process_input(self):
+        """
+        >>> w = _refl("widget")
+        >>> w.selectable_rval = True
+        >>> scr = _refl("screen")
+        >>> scr.get_cols_rows_rval = (10, 5)
+        >>> ml = MainLoop(w, [], scr)
+        >>> ml.process_input(["enter", ("mouse drag", 1, 14, 20)])
+        screen.get_cols_rows()
+        widget.selectable()
+        widget.keypress((10, 5), 'enter')
+        widget.mouse_event((10, 5), 'mouse drag', 1, 14, 20, focus=True)
+        True
+        """
+
+    def input_filter(self, keys: list[str], raw: list[int]) -> list[str]:
+        """
+        This function is passed each all the input events and raw keystroke
+        values. These values are passed to the *input_filter* function
+        passed to the constructor. That function must return a list of keys to
+        be passed to the widgets to handle. If no *input_filter* was
+        defined this implementation will return all the input events.
+        """
+        if self._input_filter:
+            return self._input_filter(keys, raw)
+        return keys
+
+    def unhandled_input(self, data: str | tuple[str, int, int, int]) -> bool | None:
+        """
+        This function is called with any input that was not handled by the
+        widgets, and calls the *unhandled_input* function passed to the
+        constructor. If no *unhandled_input* was defined then the input
+        will be ignored.
+
+        *input* is the keyboard or mouse input.
+
+        The *unhandled_input* function should return ``True`` if it handled
+        the input.
+        """
+        if self._unhandled_input:
+            return self._unhandled_input(data)
+        return False
+
+    def entering_idle(self) -> None:
+        """
+        This method is called whenever the event loop is about to enter the
+        idle state. :meth:`draw_screen` is called here to update the
+        screen when anything has changed.
+        """
+        if self.screen.started:
+            self.draw_screen()
+        else:
+            self.logger.debug(f"No redrawing screen: {self.screen!r} is not started.")
+
+    def draw_screen(self) -> None:
+        """
+        Render the widgets and paint the screen. This method is called
+        automatically from :meth:`entering_idle`.
+
+        If you modify the widgets displayed outside of handling input or
+        responding to an alarm you will need to call this method yourself
+        to repaint the screen.
+        """
+        if not self.screen_size:
+            self.screen_size = self.screen.get_cols_rows()
+            self.logger.debug(f"Screen size recalculated: {self.screen_size!r}")
+
+        canvas = self._topmost_widget.render(self.screen_size, focus=True)
+        self.screen.draw_screen(self.screen_size, canvas)
+
+
+def _refl(name: str, rval=None, loop_exit=False):
+    """
+    This function is used to test the main loop classes.
+
+    >>> scr = _refl("screen")
+    >>> scr.function("argument")
+    screen.function('argument')
+    >>> scr.callme(when="now")
+    screen.callme(when='now')
+    >>> scr.want_something_rval = 42
+    >>> x = scr.want_something()
+    screen.want_something()
+    >>> x
+    42
+
+    """
+
+    class Reflect:
+        def __init__(self, name: str, rval=None):
+            self._name = name
+            self._rval = rval
+
+        def __call__(self, *argl, **argd):
+            args = ", ".join([repr(a) for a in argl])
+            if args and argd:
+                args = f"{args}, "
+            args += ", ".join([f"{k}={v!r}" for k, v in argd.items()])
+            print(f"{self._name}({args})")
+            if loop_exit:
+                raise ExitMainLoop()
+            return self._rval
+
+        def __getattr__(self, attr):
+            if attr.endswith("_rval"):
+                raise AttributeError()
+            # print(self._name+"."+attr)
+            if hasattr(self, f"{attr}_rval"):
+                return Reflect(f"{self._name}.{attr}", getattr(self, f"{attr}_rval"))
+            return Reflect(f"{self._name}.{attr}")
+
+    return Reflect(name)
+
+
+def _test():
+    import doctest
+
+    doctest.testmod()
+
+
+if __name__ == "__main__":
+    _test()
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/select_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/select_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d950195ed91037a3d654ec8cac98a8eee0b846
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/select_loop.py
@@ -0,0 +1,230 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Select based urwid EventLoop implementation."""
+
+from __future__ import annotations
+
+import contextlib
+import heapq
+import logging
+import selectors
+import time
+import typing
+from contextlib import suppress
+from itertools import count
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Iterator
+    from concurrent.futures import Executor, Future
+
+    from typing_extensions import Literal, ParamSpec
+
+    _T = typing.TypeVar("_T")
+    _Spec = ParamSpec("_Spec")
+
+__all__ = ("SelectEventLoop",)
+
+
+class SelectEventLoop(EventLoop):
+    """
+    Event loop based on :func:`selectors.DefaultSelector.select`
+    """
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        self._alarms: list[tuple[float, int, Callable[[], typing.Any]]] = []
+        self._watch_files: dict[int, Callable[[], typing.Any]] = {}
+        self._idle_handle: int = 0
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+        self._tie_break: Iterator[int] = count()
+        self._did_something: bool = False
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> Future[_T]:
+        """Run callable in executor.
+
+        :param executor: Executor to use for running the function
+        :type executor: concurrent.futures.Executor
+        :param func: function to call
+        :type func: Callable
+        :param args: positional arguments to function
+        :type args: object
+        :param kwargs: keyword arguments to function
+        :type kwargs: object
+        :return: future object for the function call outcome.
+        :rtype: concurrent.futures.Future
+        """
+        return executor.submit(func, *args, **kwargs)
+
+    def alarm(
+        self,
+        seconds: float,
+        callback: Callable[[], typing.Any],
+    ) -> tuple[float, int, Callable[[], typing.Any]]:
+        """
+        Call callback() a given time from now.  No parameters are
+        passed to callback.
+
+        Returns a handle that may be passed to remove_alarm()
+
+        seconds -- floating point time to wait before calling callback
+        callback -- function to call from event loop
+        """
+        tm = time.time() + seconds
+        handle = (tm, next(self._tie_break), callback)
+        heapq.heappush(self._alarms, handle)
+        return handle
+
+    def remove_alarm(self, handle: tuple[float, int, Callable[[], typing.Any]]) -> bool:
+        """
+        Remove an alarm.
+
+        Returns True if the alarm exists, False otherwise
+        """
+        try:
+            self._alarms.remove(handle)
+            heapq.heapify(self._alarms)
+
+        except ValueError:
+            return False
+
+        return True
+
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int:
+        """
+        Call callback() when fd has some data to read.  No parameters
+        are passed to callback.
+
+        Returns a handle that may be passed to remove_watch_file()
+
+        fd -- file descriptor to watch for input
+        callback -- function to call when input is available
+        """
+        self._watch_files[fd] = callback
+        return fd
+
+    def remove_watch_file(self, handle: int) -> bool:
+        """
+        Remove an input file.
+
+        Returns True if the input file exists, False otherwise
+        """
+        if handle in self._watch_files:
+            del self._watch_files[handle]
+            return True
+        return False
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a callback for entering idle.
+
+        Returns a handle that may be passed to remove_idle()
+        """
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """
+        Remove an idle callback.
+
+        Returns True if the handle was removed.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def _entering_idle(self) -> None:
+        """
+        Call all the registered idle callbacks.
+        """
+        for callback in self._idle_callbacks.values():
+            callback()
+
+    def run(self) -> None:
+        """
+        Start the event loop.  Exit the loop when any callback raises
+        an exception.  If ExitMainLoop is raised, exit cleanly.
+        """
+        with contextlib.suppress(ExitMainLoop):
+            self._did_something = True
+            while True:
+                with suppress(InterruptedError):
+                    self._loop()
+
+    def _loop(self) -> None:
+        """
+        A single iteration of the event loop
+        """
+        tm: float | Literal["idle"] | None = None
+
+        with selectors.DefaultSelector() as selector:
+            for fd, callback in self._watch_files.items():
+                selector.register(fd, selectors.EVENT_READ, callback)
+
+            if self._alarms or self._did_something:
+                timeout = 0.0
+
+                if self._alarms:
+                    timeout_ = self._alarms[0][0]
+                    tm = timeout_
+                    timeout = max(timeout, timeout_ - time.time())
+
+                if self._did_something and (not self._alarms or (self._alarms and timeout > 0)):
+                    timeout = 0.0
+                    tm = "idle"
+
+                self.logger.debug(f"Waiting for input: timeout={timeout!r}")
+                ready = [event for event, _ in selector.select(timeout)]
+
+            elif self._watch_files:
+                self.logger.debug("Waiting for input: timeout")
+                ready = [event for event, _ in selector.select()]
+            else:
+                ready = []
+
+        if not ready:
+            if tm == "idle":
+                self.logger.debug("No input, entering IDLE")
+                self._entering_idle()
+                self._did_something = False
+            elif tm is not None:
+                # must have been a timeout
+                tm, _tie_break, alarm_callback = heapq.heappop(self._alarms)
+                self.logger.debug(f"No input in timeout, calling scheduled {alarm_callback!r}")
+                alarm_callback()
+                self._did_something = True
+
+        self.logger.debug("Processing input")
+        for record in ready:
+            record.data()
+            self._did_something = True
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/tornado_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/tornado_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ab444f09aae0a1ee240d063f957465744f662f7
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/tornado_loop.py
@@ -0,0 +1,213 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Tornado IOLoop based urwid EventLoop implementation.
+
+Tornado library is required.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import logging
+import typing
+from contextlib import suppress
+
+from tornado import ioloop
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable
+    from concurrent.futures import Executor
+
+    from typing_extensions import Literal, ParamSpec
+
+    _Spec = ParamSpec("_Spec")
+    _T = typing.TypeVar("_T")
+
+__all__ = ("TornadoEventLoop",)
+
+
+class TornadoEventLoop(EventLoop):
+    """This is an Urwid-specific event loop to plug into its MainLoop.
+    It acts as an adaptor for Tornado's IOLoop which does all
+    heavy lifting except idle-callbacks.
+    """
+
+    def __init__(self, loop: ioloop.IOLoop | None = None) -> None:
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        if loop:
+            self._loop: ioloop.IOLoop = loop
+        else:
+            try:
+                asyncio.get_running_loop()
+            except RuntimeError:
+                asyncio.set_event_loop(asyncio.new_event_loop())
+
+            self._loop = ioloop.IOLoop.current()
+
+        self._pending_alarms: dict[object, int] = {}
+        self._watch_handles: dict[int, int] = {}  # { : }
+        self._max_watch_handle: int = 0
+        self._exc: BaseException | None = None
+
+        self._idle_asyncio_handle: object | None = None
+        self._idle_handle: int = 0
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+
+    def _also_call_idle(self, callback: Callable[_Spec, _T]) -> Callable[_Spec, _T]:
+        """
+        Wrap the callback to also call _entering_idle.
+        """
+
+        @functools.wraps(callback)
+        def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T:
+            if not self._idle_asyncio_handle:
+                self._idle_asyncio_handle = self._loop.call_later(0, self._entering_idle)
+            return callback(*args, **kwargs)
+
+        return wrapper
+
+    def _entering_idle(self) -> None:
+        """
+        Call all the registered idle callbacks.
+        """
+        try:
+            for callback in self._idle_callbacks.values():
+                callback()
+        finally:
+            self._idle_asyncio_handle = None
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> asyncio.Future[_T]:
+        """Run callable in executor.
+
+        :param executor: Executor to use for running the function
+        :type executor: concurrent.futures.Executor
+        :param func: function to call
+        :type func: Callable
+        :param args: arguments to function (positional only)
+        :type args: object
+        :param kwargs: keyword arguments to function (keyword only)
+        :type kwargs: object
+        :return: future object for the function call outcome.
+        :rtype: asyncio.Future
+        """
+        return self._loop.run_in_executor(executor, functools.partial(func, *args, **kwargs))
+
+    def alarm(self, seconds: float, callback: Callable[[], typing.Any]):
+        @self._also_call_idle
+        @functools.wraps(callback)
+        def wrapped() -> None:
+            with suppress(KeyError):
+                del self._pending_alarms[handle]
+
+            self.handle_exit(callback)()
+
+        handle = self._loop.add_timeout(self._loop.time() + seconds, wrapped)
+        self._pending_alarms[handle] = 1
+        return handle
+
+    def remove_alarm(self, handle: object) -> bool:
+        self._loop.remove_timeout(handle)
+        try:
+            del self._pending_alarms[handle]
+        except KeyError:
+            return False
+
+        return True
+
+    def watch_file(self, fd: int, callback: Callable[[], _T]) -> int:
+        @self._also_call_idle
+        def handler(_fd: int, _events: int) -> None:
+            self.handle_exit(callback)()
+
+        self._loop.add_handler(fd, handler, ioloop.IOLoop.READ)
+        self._max_watch_handle += 1
+        handle = self._max_watch_handle
+        self._watch_handles[handle] = fd
+        return handle
+
+    def remove_watch_file(self, handle: int) -> bool:
+        if (fd := self._watch_handles.pop(handle, None)) is not None:
+            self._loop.remove_handler(fd)
+            return True
+
+        return False
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a callback for entering idle.
+
+        Returns a handle that may be passed to remove_idle()
+        """
+        # XXX there's no such thing as "idle" in most event loops; this fakes
+        # it by adding extra callback to the timer and file watch callbacks.
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """
+        Remove an idle callback.
+
+        Returns True if the handle was removed.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def handle_exit(self, f: Callable[_Spec, _T]) -> Callable[_Spec, _T | Literal[False]]:
+        @functools.wraps(f)
+        def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | Literal[False]:
+            try:
+                return f(*args, **kwargs)
+            except ExitMainLoop:
+                pass  # handled later
+            except Exception as exc:
+                self._exc = exc
+
+            if self._idle_asyncio_handle:
+                # clean it up to prevent old callbacks
+                # from messing things up if loop is restarted
+                self._loop.remove_timeout(self._idle_asyncio_handle)
+                self._idle_asyncio_handle = None
+
+            self._loop.stop()
+            return False
+
+        return wrapper
+
+    def run(self) -> None:
+        self._loop.start()
+        if self._exc:
+            exc, self._exc = self._exc, None
+            raise exc.with_traceback(exc.__traceback__)
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/trio_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/trio_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..1270679263cb1e847da0bd4e5e7d3d189fdbec76
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/trio_loop.py
@@ -0,0 +1,309 @@
+# Urwid main loop code using Python-3.5 features (Trio, Curio, etc)
+#    Copyright (C) 2018 Toshio Kuratomi
+#    Copyright (C) 2019 Tamas Nepusz
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Trio Runner based urwid EventLoop implementation.
+
+Trio library is required.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import typing
+
+import trio
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if sys.version_info < (3, 11):
+    from exceptiongroup import BaseExceptionGroup  # pylint: disable=redefined-builtin  # backport
+
+if typing.TYPE_CHECKING:
+    import io
+    from collections.abc import Awaitable, Callable, Hashable, Mapping
+
+    from typing_extensions import Concatenate, ParamSpec
+
+    _Spec = ParamSpec("_Spec")
+
+__all__ = ("TrioEventLoop",)
+
+
+class _TrioIdleCallbackInstrument(trio.abc.Instrument):
+    """IDLE callbacks emulation helper."""
+
+    __slots__ = ("idle_callbacks",)
+
+    def __init__(self, idle_callbacks: Mapping[Hashable, Callable[[], typing.Any]]):
+        self.idle_callbacks = idle_callbacks
+
+    def before_io_wait(self, timeout: float) -> None:
+        if timeout > 0:
+            for idle_callback in self.idle_callbacks.values():
+                idle_callback()
+
+
+class TrioEventLoop(EventLoop):
+    """
+    Event loop based on the ``trio`` module.
+
+    ``trio`` is an async library for Python 3.5 and later.
+    """
+
+    def __init__(self) -> None:
+        """Constructor."""
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+
+        self._idle_handle = 0
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+        self._pending_tasks: list[tuple[Callable[_Spec, Awaitable], trio.CancelScope, _Spec.args]] = []
+
+        self._nursery: trio.Nursery | None = None
+
+        self._sleep = trio.sleep
+        self._wait_readable = trio.lowlevel.wait_readable
+
+    def alarm(
+        self,
+        seconds: float,
+        callback: Callable[[], typing.Any],
+    ) -> trio.CancelScope:
+        """Calls `callback()` a given time from now.
+
+        :param seconds: time in seconds to wait before calling the callback
+        :type seconds: float
+        :param callback: function to call from the event loop
+        :type callback: Callable[[], typing.Any]
+        :return: a handle that may be passed to `remove_alarm()`
+        :rtype: trio.CancelScope
+
+        No parameters are passed to the callback.
+        """
+        return self._start_task(self._alarm_task, seconds, callback)
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """Calls `callback()` when the event loop enters the idle state.
+
+        There is no such thing as being idle in a Trio event loop so we
+        simulate it by repeatedly calling `callback()` with a short delay.
+        """
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def remove_alarm(self, handle: trio.CancelScope) -> bool:
+        """Removes an alarm.
+
+        Parameters:
+            handle: the handle of the alarm to remove
+        """
+        return self._cancel_scope(handle)
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """Removes an idle callback.
+
+        Parameters:
+            handle: the handle of the idle callback to remove
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def remove_watch_file(self, handle: trio.CancelScope) -> bool:
+        """Removes a file descriptor being watched for input.
+
+        Parameters:
+            handle: the handle of the file descriptor callback to remove
+
+        Returns:
+            True if the file descriptor was watched, False otherwise
+        """
+        return self._cancel_scope(handle)
+
+    def _cancel_scope(self, scope: trio.CancelScope) -> bool:
+        """Cancels the given Trio cancellation scope.
+
+        Returns:
+            True if the scope was cancelled, False if it was cancelled already
+            before invoking this function
+        """
+        existed = not scope.cancel_called
+        scope.cancel()
+        return existed
+
+    def run(self) -> None:
+        """Starts the event loop. Exits the loop when any callback raises an
+        exception. If ExitMainLoop is raised, exits cleanly.
+        """
+
+        emulate_idle_callbacks = _TrioIdleCallbackInstrument(self._idle_callbacks)
+
+        try:
+            trio.run(self._main_task, instruments=[emulate_idle_callbacks])
+        except BaseException as exc:
+            self._handle_main_loop_exception(exc)
+
+    async def run_async(self) -> None:
+        """Starts the main loop and blocks asynchronously until the main loop exits.
+
+        This allows one to embed an urwid app in a Trio app even if the Trio event loop is already running.
+        Example::
+
+            with trio.open_nursery() as nursery:
+                event_loop = urwid.TrioEventLoop()
+
+                # [...launch other async tasks in the nursery...]
+
+                loop = urwid.MainLoop(widget, event_loop=event_loop)
+                with loop.start():
+                    await event_loop.run_async()
+
+                nursery.cancel_scope.cancel()
+        """
+
+        emulate_idle_callbacks = _TrioIdleCallbackInstrument(self._idle_callbacks)
+
+        try:
+            trio.lowlevel.add_instrument(emulate_idle_callbacks)
+            try:
+                await self._main_task()
+            finally:
+                trio.lowlevel.remove_instrument(emulate_idle_callbacks)
+        except BaseException as exc:
+            self._handle_main_loop_exception(exc)
+
+    def watch_file(
+        self,
+        fd: int | io.IOBase,
+        callback: Callable[[], typing.Any],
+    ) -> trio.CancelScope:
+        """Calls `callback()` when the given file descriptor has some data
+        to read. No parameters are passed to the callback.
+
+        Parameters:
+            fd: file descriptor to watch for input
+            callback: function to call when some input is available
+
+        Returns:
+            a handle that may be passed to `remove_watch_file()`
+        """
+        return self._start_task(self._watch_task, fd, callback)
+
+    async def _alarm_task(
+        self,
+        scope: trio.CancelScope,
+        seconds: float,
+        callback: Callable[[], typing.Any],
+    ) -> None:
+        """Asynchronous task that sleeps for a given number of seconds and then
+        calls the given callback.
+
+        Parameters:
+            scope: the cancellation scope that can be used to cancel the task
+            seconds: the number of seconds to wait
+            callback: the callback to call
+        """
+        with scope:
+            await self._sleep(seconds)
+            callback()
+
+    def _handle_main_loop_exception(self, exc: BaseException) -> None:
+        """Handles exceptions raised from the main loop, catching ExitMainLoop
+        instead of letting it propagate through.
+
+        Note that since Trio may collect multiple exceptions from tasks into an ExceptionGroup,
+        we cannot simply use a try..catch clause, we need a helper function like this.
+        """
+        self._idle_callbacks.clear()
+        if isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1:
+            exc = exc.exceptions[0]
+
+        if isinstance(exc, ExitMainLoop):
+            return
+
+        raise exc.with_traceback(exc.__traceback__) from None
+
+    async def _main_task(self) -> None:
+        """Main Trio task that opens a nursery and then sleeps until the user
+        exits the app by raising ExitMainLoop.
+        """
+        try:
+            async with trio.open_nursery() as self._nursery:
+                self._schedule_pending_tasks()
+                await trio.sleep_forever()
+        finally:
+            self._nursery = None
+
+    def _schedule_pending_tasks(self) -> None:
+        """Schedules all pending asynchronous tasks that were created before
+        the nursery to be executed on the nursery soon.
+        """
+        for task, scope, args in self._pending_tasks:
+            self._nursery.start_soon(task, scope, *args)
+        self._pending_tasks.clear()
+
+    def _start_task(
+        self,
+        task: Callable[Concatenate[trio.CancelScope, _Spec], Awaitable],
+        *args: _Spec.args,
+    ) -> trio.CancelScope:
+        """Starts an asynchronous task in the Trio nursery managed by the
+        main loop. If the nursery has not started yet, store a reference to
+        the task and the arguments so we can start the task when the nursery
+        is open.
+
+        Parameters:
+            task: a Trio task to run
+
+        Returns:
+            a cancellation scope for the Trio task
+        """
+        scope = trio.CancelScope()
+        if self._nursery:
+            self._nursery.start_soon(task, scope, *args)
+        else:
+            self._pending_tasks.append((task, scope, args))
+        return scope
+
+    async def _watch_task(
+        self,
+        scope: trio.CancelScope,
+        fd: int | io.IOBase,
+        callback: Callable[[], typing.Any],
+    ) -> None:
+        """Asynchronous task that watches the given file descriptor and calls
+        the given callback whenever the file descriptor becomes readable.
+
+        Parameters:
+            scope: the cancellation scope that can be used to cancel the task
+            fd: the file descriptor to watch
+            callback: the callback to call
+        """
+        with scope:
+            # We check for the scope being cancelled before calling
+            # wait_readable because if callback cancels the scope, fd might be
+            # closed and calling wait_readable with a closed fd does not work.
+            while not scope.cancel_called:
+                await self._wait_readable(fd)
+                callback()
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/twisted_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/twisted_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bb3cca39a82b1d4256f36f773d90d3ba5ec4367
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/twisted_loop.py
@@ -0,0 +1,270 @@
+# Urwid main loop code
+#    Copyright (C) 2004-2012  Ian Ward
+#    Copyright (C) 2008 Walter Mundt
+#    Copyright (C) 2009 Andrew Psaltis
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""Twisted Reactor based urwid EventLoop implementation.
+
+Twisted library is required.
+"""
+
+from __future__ import annotations
+
+import functools
+import logging
+import sys
+import typing
+
+from twisted.internet.abstract import FileDescriptor
+from twisted.internet.error import AlreadyCalled, AlreadyCancelled
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable
+    from concurrent.futures import Executor, Future
+
+    from twisted.internet.base import DelayedCall, ReactorBase
+    from typing_extensions import ParamSpec
+
+    _Spec = ParamSpec("_Spec")
+    _T = typing.TypeVar("_T")
+
+__all__ = ("TwistedEventLoop",)
+
+
+class _TwistedInputDescriptor(FileDescriptor):
+    def __init__(self, reactor: ReactorBase, fd: int, cb: Callable[[], typing.Any]) -> None:
+        self._fileno = fd
+        self.cb = cb
+        super().__init__(reactor)  # ReactorBase implement full API as required in interfaces
+
+    def fileno(self) -> int:
+        return self._fileno
+
+    def doRead(self):
+        return self.cb()
+
+    def getHost(self):
+        raise NotImplementedError("No network operation expected")
+
+    def getPeer(self):
+        raise NotImplementedError("No network operation expected")
+
+    def writeSomeData(self, data: bytes) -> None:
+        raise NotImplementedError("Reduced functionality: read-only")
+
+
+class TwistedEventLoop(EventLoop):
+    """
+    Event loop based on Twisted_
+    """
+
+    _idle_emulation_delay = 1.0 / 256  # a short time (in seconds)
+
+    def __init__(self, reactor: ReactorBase | None = None, manage_reactor: bool = True) -> None:
+        """
+        :param reactor: reactor to use
+        :type reactor: :class:`twisted.internet.reactor`.
+        :param: manage_reactor: `True` if you want this event loop to run
+                                and stop the reactor.
+        :type manage_reactor: boolean
+
+        .. WARNING::
+           Twisted's reactor doesn't like to be stopped and run again.  If you
+           need to stop and run your :class:`MainLoop`, consider setting
+           ``manage_reactor=False`` and take care of running/stopping the reactor
+           at the beginning/ending of your program yourself.
+
+           You can also forego using :class:`MainLoop`'s run() entirely, and
+           instead call start() and stop() before and after starting the
+           reactor.
+
+        .. _Twisted: https://twisted.org/
+        """
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        if reactor is None:
+            import twisted.internet.reactor
+
+            reactor = twisted.internet.reactor
+        self.reactor: ReactorBase = reactor
+        self._watch_files: dict[int, _TwistedInputDescriptor] = {}
+        self._idle_handle: int = 0
+        self._twisted_idle_enabled = False
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+        self._exc: BaseException | None = None
+        self.manage_reactor = manage_reactor
+        self._enable_twisted_idle()
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[..., _T],
+        *args: object,
+        **kwargs: object,
+    ) -> Future[_T]:
+        raise NotImplementedError(
+            "Twisted implement it's own ThreadPool executor. Please use native API for call:\n"
+            "'threads.deferToThread(Callable[..., Any], *args, **kwargs)'\n"
+            "And use 'addCallback' api for callbacks:\n"
+            "'threads.deferToThread(Callable[..., T], *args, **kwargs).addCallback(Callable[[T], None])'"
+        )
+
+    def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> DelayedCall:
+        """
+        Call callback() a given time from now.  No parameters are
+        passed to callback.
+
+        Returns a handle that may be passed to remove_alarm()
+
+        seconds -- floating point time to wait before calling callback
+        callback -- function to call from event loop
+        """
+        handle = self.reactor.callLater(seconds, self.handle_exit(callback))
+        return handle
+
+    def remove_alarm(self, handle: DelayedCall) -> bool:
+        """
+        Remove an alarm.
+
+        Returns True if the alarm exists, False otherwise
+        """
+        try:
+            handle.cancel()
+
+        except (AlreadyCancelled, AlreadyCalled):
+            return False
+
+        return True
+
+    def watch_file(self, fd: int, callback: Callable[[], typing.Any]) -> int:
+        """
+        Call callback() when fd has some data to read.  No parameters
+        are passed to callback.
+
+        Returns a handle that may be passed to remove_watch_file()
+
+        fd -- file descriptor to watch for input
+        callback -- function to call when input is available
+        """
+        ind = _TwistedInputDescriptor(self.reactor, fd, self.handle_exit(callback))
+        self._watch_files[fd] = ind
+        self.reactor.addReader(ind)
+        return fd
+
+    def remove_watch_file(self, handle: int) -> bool:
+        """
+        Remove an input file.
+
+        Returns True if the input file exists, False otherwise
+        """
+        if handle in self._watch_files:
+            self.reactor.removeReader(self._watch_files[handle])
+            del self._watch_files[handle]
+            return True
+        return False
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a callback for entering idle.
+
+        Returns a handle that may be passed to remove_enter_idle()
+        """
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def _enable_twisted_idle(self) -> None:
+        """
+        Twisted's reactors don't have an idle or enter-idle callback
+        so the best we can do for now is to set a timer event in a very
+        short time to approximate an enter-idle callback.
+
+        .. WARNING::
+           This will perform worse than the other event loops until we can find a
+           fix or workaround
+        """
+        if self._twisted_idle_enabled:
+            return
+        self.reactor.callLater(
+            self._idle_emulation_delay,
+            self.handle_exit(self._twisted_idle_callback, enable_idle=False),
+        )
+        self._twisted_idle_enabled = True
+
+    def _twisted_idle_callback(self) -> None:
+        for callback in self._idle_callbacks.values():
+            callback()
+        self._twisted_idle_enabled = False
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """
+        Remove an idle callback.
+
+        Returns True if the handle was removed.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+        return True
+
+    def run(self) -> None:
+        """
+        Start the event loop.  Exit the loop when any callback raises
+        an exception.  If ExitMainLoop is raised, exit cleanly.
+        """
+        if not self.manage_reactor:
+            return
+        self.reactor.run()
+        if self._exc:
+            # An exception caused us to exit, raise it now
+            exc = self._exc
+            self._exc = None
+            raise exc.with_traceback(exc.__traceback__)
+
+    def handle_exit(self, f: Callable[_Spec, _T], enable_idle: bool = True) -> Callable[_Spec, _T | None]:
+        """
+        Decorator that cleanly exits the :class:`TwistedEventLoop` if
+        :class:`ExitMainLoop` is thrown inside of the wrapped function. Store the
+        exception info if some other exception occurs, it will be reraised after
+        the loop quits.
+
+        *f* -- function to be wrapped
+        """
+
+        @functools.wraps(f)
+        def wrapper(*args: _Spec.args, **kwargs: _Spec.kwargs) -> _T | None:
+            rval = None
+            try:
+                rval = f(*args, **kwargs)
+            except ExitMainLoop:
+                if self.manage_reactor:
+                    self.reactor.stop()
+            except BaseException as exc:
+                print(sys.exc_info())
+                self._exc = exc
+                if self.manage_reactor:
+                    self.reactor.crash()
+            if enable_idle:
+                self._enable_twisted_idle()
+            return rval
+
+        return wrapper
diff --git a/python/user_packages/Python313/site-packages/urwid/event_loop/zmq_loop.py b/python/user_packages/Python313/site-packages/urwid/event_loop/zmq_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..245746b169bd23b92196676cb9db36b43fc78c2e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/event_loop/zmq_loop.py
@@ -0,0 +1,277 @@
+# Urwid main loop code using ZeroMQ queues
+#    Copyright (C) 2019 Dave Jones
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+"""ZeroMQ based urwid EventLoop implementation.
+
+`ZeroMQ `_ library is required.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import errno
+import heapq
+import logging
+import os
+import time
+import typing
+from itertools import count
+
+import zmq
+
+from .abstract_loop import EventLoop, ExitMainLoop
+
+if typing.TYPE_CHECKING:
+    import io
+    from collections.abc import Callable
+    from concurrent.futures import Executor, Future
+
+    from typing_extensions import ParamSpec
+
+    ZMQAlarmHandle = typing.TypeVar("ZMQAlarmHandle")
+    _T = typing.TypeVar("_T")
+    _Spec = ParamSpec("_Spec")
+
+
+class ZMQEventLoop(EventLoop):
+    """
+    This class is an urwid event loop for `ZeroMQ`_ applications. It is very
+    similar to :class:`SelectEventLoop`, supporting the usual :meth:`alarm`
+    events and file watching (:meth:`watch_file`) capabilities, but also
+    incorporates the ability to watch zmq queues for events
+    (:meth:`watch_queue`).
+
+    .. _ZeroMQ: https://zeromq.org/
+    """
+
+    _alarm_break = count()
+
+    def __init__(self) -> None:
+        super().__init__()
+        self.logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
+        self._did_something = True
+        self._alarms: list[tuple[float, int, Callable[[], typing.Any]]] = []
+        self._poller = zmq.Poller()
+        self._queue_callbacks: dict[int, Callable[[], typing.Any]] = {}
+        self._idle_handle = 0
+        self._idle_callbacks: dict[int, Callable[[], typing.Any]] = {}
+
+    def run_in_executor(
+        self,
+        executor: Executor,
+        func: Callable[_Spec, _T],
+        *args: _Spec.args,
+        **kwargs: _Spec.kwargs,
+    ) -> Future[_T]:
+        """Run callable in executor.
+
+        :param executor: Executor to use for running the function
+        :type executor: concurrent.futures.Executor
+        :param func: function to call
+        :type func: Callable
+        :param args: positional arguments to function
+        :type args: object
+        :param kwargs: keyword arguments to function
+        :type kwargs: object
+        :return: future object for the function call outcome.
+        :rtype: concurrent.futures.Future
+        """
+        return executor.submit(func, *args, **kwargs)
+
+    def alarm(self, seconds: float, callback: Callable[[], typing.Any]) -> ZMQAlarmHandle:
+        """
+        Call *callback* a given time from now. No parameters are passed to
+        callback. Returns a handle that may be passed to :meth:`remove_alarm`.
+
+        :param float seconds:
+            floating point time to wait before calling callback.
+
+        :param callback:
+            function to call from event loop.
+        """
+        handle = (time.time() + seconds, next(self._alarm_break), callback)
+        heapq.heappush(self._alarms, handle)
+        return handle
+
+    def remove_alarm(self, handle: ZMQAlarmHandle) -> bool:
+        """
+        Remove an alarm. Returns ``True`` if the alarm exists, ``False``
+        otherwise.
+        """
+        try:
+            self._alarms.remove(handle)
+            heapq.heapify(self._alarms)
+
+        except ValueError:
+            return False
+
+        return True
+
+    def watch_queue(
+        self,
+        queue: zmq.Socket,
+        callback: Callable[[], typing.Any],
+        flags: int = zmq.POLLIN,
+    ) -> zmq.Socket:
+        """
+        Call *callback* when zmq *queue* has something to read (when *flags* is
+        set to ``POLLIN``, the default) or is available to write (when *flags*
+        is set to ``POLLOUT``). No parameters are passed to the callback.
+        Returns a handle that may be passed to :meth:`remove_watch_queue`.
+
+        :param queue:
+            The zmq queue to poll.
+
+        :param callback:
+            The function to call when the poll is successful.
+
+        :param int flags:
+            The condition to monitor on the queue (defaults to ``POLLIN``).
+        """
+        if queue in self._queue_callbacks:
+            raise ValueError(f"already watching {queue!r}")
+        self._poller.register(queue, flags)
+        self._queue_callbacks[queue] = callback
+        return queue
+
+    def watch_file(
+        self,
+        fd: int | io.TextIOWrapper,
+        callback: Callable[[], typing.Any],
+        flags: int = zmq.POLLIN,
+    ) -> io.TextIOWrapper:
+        """
+        Call *callback* when *fd* has some data to read. No parameters are
+        passed to the callback. The *flags* are as for :meth:`watch_queue`.
+        Returns a handle that may be passed to :meth:`remove_watch_file`.
+
+        :param fd:
+            The file-like object, or fileno to monitor.
+
+        :param callback:
+            The function to call when the file has data available.
+
+        :param int flags:
+            The condition to monitor on the file (defaults to ``POLLIN``).
+        """
+        if isinstance(fd, int):
+            fd = os.fdopen(fd)
+        self._poller.register(fd, flags)
+        self._queue_callbacks[fd.fileno()] = callback
+        return fd
+
+    def remove_watch_queue(self, handle: zmq.Socket) -> bool:
+        """
+        Remove a queue from background polling. Returns ``True`` if the queue
+        was being monitored, ``False`` otherwise.
+        """
+        try:
+            try:
+                self._poller.unregister(handle)
+            finally:
+                self._queue_callbacks.pop(handle, None)
+
+        except KeyError:
+            return False
+
+        return True
+
+    def remove_watch_file(self, handle: io.TextIOWrapper) -> bool:
+        """
+        Remove a file from background polling. Returns ``True`` if the file was
+        being monitored, ``False`` otherwise.
+        """
+        try:
+            try:
+                self._poller.unregister(handle)
+            finally:
+                self._queue_callbacks.pop(handle.fileno(), None)
+
+        except KeyError:
+            return False
+
+        return True
+
+    def enter_idle(self, callback: Callable[[], typing.Any]) -> int:
+        """
+        Add a *callback* to be executed when the event loop detects it is idle.
+        Returns a handle that may be passed to :meth:`remove_enter_idle`.
+        """
+        self._idle_handle += 1
+        self._idle_callbacks[self._idle_handle] = callback
+        return self._idle_handle
+
+    def remove_enter_idle(self, handle: int) -> bool:
+        """
+        Remove an idle callback. Returns ``True`` if *handle* was removed,
+        ``False`` otherwise.
+        """
+        try:
+            del self._idle_callbacks[handle]
+        except KeyError:
+            return False
+
+        return True
+
+    def _entering_idle(self) -> None:
+        for callback in list(self._idle_callbacks.values()):
+            callback()
+
+    def run(self) -> None:
+        """
+        Start the event loop. Exit the loop when any callback raises an
+        exception. If :exc:`ExitMainLoop` is raised, exit cleanly.
+        """
+        with contextlib.suppress(ExitMainLoop):
+            while True:
+                try:
+                    self._loop()
+                except zmq.error.ZMQError as exc:  # noqa: PERF203
+                    if exc.errno != errno.EINTR:
+                        raise
+
+    def _loop(self) -> None:
+        """
+        A single iteration of the event loop.
+        """
+        state = "wait"  # default state not expecting any action
+        if self._alarms or self._did_something:
+            timeout = 0
+            if self._alarms:
+                state = "alarm"
+                timeout = max(0.0, self._alarms[0][0] - time.time())
+            if self._did_something and (not self._alarms or (self._alarms and timeout > 0)):
+                state = "idle"
+                timeout = 0
+            ready = dict(self._poller.poll(timeout * 1000))
+        else:
+            ready = dict(self._poller.poll())
+
+        if not ready:
+            if state == "idle":
+                self._entering_idle()
+                self._did_something = False
+            elif state == "alarm":
+                _due, _tie_break, callback = heapq.heappop(self._alarms)
+                callback()
+                self._did_something = True
+
+        for queue in ready:
+            self._queue_callbacks[queue]()
+            self._did_something = True
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__init__.py b/python/user_packages/Python313/site-packages/urwid/widget/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd842df75ce4a6a917e1eeb3bc92e1a951717610
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/__init__.py
@@ -0,0 +1,193 @@
+from __future__ import annotations
+
+from .attr_map import AttrMap, AttrMapError
+from .attr_wrap import AttrWrap
+from .bar_graph import BarGraph, BarGraphError, BarGraphMeta, GraphVScale, scale_bar_values
+from .big_text import BigText
+from .box_adapter import BoxAdapter, BoxAdapterError
+from .columns import Columns, ColumnsError, ColumnsWarning
+from .constants import (
+    RELATIVE_100,
+    Align,
+    Sizing,
+    VAlign,
+    WHSettings,
+    WrapMode,
+    normalize_align,
+    normalize_height,
+    normalize_valign,
+    normalize_width,
+    simplify_align,
+    simplify_height,
+    simplify_valign,
+    simplify_width,
+)
+from .container import WidgetContainerListContentsMixin, WidgetContainerMixin
+from .divider import Divider
+from .edit import Edit, EditError, IntEdit
+from .filler import Filler, FillerError, calculate_top_bottom_filler
+from .frame import Frame, FrameError
+from .grid_flow import GridFlow, GridFlowError, GridFlowWarning
+from .line_box import LineBox
+from .listbox import ListBox, ListBoxError, ListWalker, ListWalkerError, SimpleFocusListWalker, SimpleListWalker
+from .monitored_list import MonitoredFocusList, MonitoredList
+from .overlay import Overlay, OverlayError, OverlayWarning
+from .padding import Padding, PaddingError, PaddingWarning, calculate_left_right_padding
+from .pile import Pile, PileError, PileWarning
+from .popup import PopUpLauncher, PopUpTarget
+from .progress_bar import ProgressBar
+from .scrollable import Scrollable, ScrollableError, ScrollBar
+from .solid_fill import SolidFill
+from .text import Text, TextError
+from .treetools import ParentNode, TreeListBox, TreeNode, TreeWalker, TreeWidget, TreeWidgetError
+from .widget import (
+    Widget,
+    WidgetError,
+    WidgetMeta,
+    WidgetWarning,
+    WidgetWrap,
+    WidgetWrapError,
+    delegate_to_widget_mixin,
+    fixed_size,
+    nocache_widget_render,
+    nocache_widget_render_instance,
+)
+from .widget_decoration import WidgetDecoration, WidgetDisable, WidgetPlaceholder
+from .wimp import Button, CheckBox, CheckBoxError, RadioButton, SelectableIcon
+
+__all__ = (
+    "ANY",
+    "BOTTOM",
+    "BOX",
+    "CENTER",
+    "CLIP",
+    "ELLIPSIS",
+    "FIXED",
+    "FLOW",
+    "GIVEN",
+    "LEFT",
+    "MIDDLE",
+    "PACK",
+    "RELATIVE",
+    "RELATIVE_100",
+    "RIGHT",
+    "SPACE",
+    "TOP",
+    "WEIGHT",
+    "Align",
+    "AttrMap",
+    "AttrMapError",
+    "AttrWrap",
+    "BarGraph",
+    "BarGraphError",
+    "BarGraphMeta",
+    "BigText",
+    "BoxAdapter",
+    "BoxAdapterError",
+    "Button",
+    "CheckBox",
+    "CheckBoxError",
+    "Columns",
+    "ColumnsError",
+    "ColumnsWarning",
+    "Divider",
+    "Edit",
+    "EditError",
+    "Filler",
+    "FillerError",
+    "Frame",
+    "FrameError",
+    "GraphVScale",
+    "GridFlow",
+    "GridFlowError",
+    "GridFlowWarning",
+    "IntEdit",
+    "LineBox",
+    "ListBox",
+    "ListBoxError",
+    "ListWalker",
+    "ListWalkerError",
+    "MonitoredFocusList",
+    "MonitoredList",
+    "Overlay",
+    "OverlayError",
+    "OverlayWarning",
+    "Padding",
+    "PaddingError",
+    "PaddingWarning",
+    "ParentNode",
+    "Pile",
+    "PileError",
+    "PileWarning",
+    "PopUpLauncher",
+    "PopUpTarget",
+    "ProgressBar",
+    "RadioButton",
+    "ScrollBar",
+    "Scrollable",
+    "ScrollableError",
+    "SelectableIcon",
+    "SimpleFocusListWalker",
+    "SimpleListWalker",
+    "Sizing",
+    "SolidFill",
+    "Text",
+    "TextError",
+    "TreeListBox",
+    "TreeNode",
+    "TreeWalker",
+    "TreeWidget",
+    "TreeWidgetError",
+    "VAlign",
+    "WHSettings",
+    "Widget",
+    "WidgetContainerListContentsMixin",
+    "WidgetContainerMixin",
+    "WidgetDecoration",
+    "WidgetDisable",
+    "WidgetError",
+    "WidgetMeta",
+    "WidgetPlaceholder",
+    "WidgetWarning",
+    "WidgetWrap",
+    "WidgetWrapError",
+    "WrapMode",
+    "calculate_left_right_padding",
+    "calculate_top_bottom_filler",
+    "delegate_to_widget_mixin",
+    "fixed_size",
+    "nocache_widget_render",
+    "nocache_widget_render_instance",
+    "normalize_align",
+    "normalize_height",
+    "normalize_valign",
+    "normalize_width",
+    "scale_bar_values",
+    "simplify_align",
+    "simplify_height",
+    "simplify_valign",
+    "simplify_width",
+)
+
+# Backward compatibility
+FLOW = Sizing.FLOW
+BOX = Sizing.BOX
+FIXED = Sizing.FIXED
+
+LEFT = Align.LEFT
+RIGHT = Align.RIGHT
+CENTER = Align.CENTER
+
+TOP = VAlign.TOP
+MIDDLE = VAlign.MIDDLE
+BOTTOM = VAlign.BOTTOM
+
+SPACE = WrapMode.SPACE
+ANY = WrapMode.ANY
+CLIP = WrapMode.CLIP
+ELLIPSIS = WrapMode.ELLIPSIS
+
+PACK = WHSettings.PACK
+GIVEN = WHSettings.GIVEN
+RELATIVE = WHSettings.RELATIVE
+WEIGHT = WHSettings.WEIGHT
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a5137d160cba99810dd96e8feecb664fab87c00
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/__init__.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_map.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_map.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5ee429e2e010a7eb45cee98b2d5db8a8d14c7d0
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_map.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_wrap.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_wrap.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c64cca52c6a2d4797ca0582a8605202ad42a40a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/attr_wrap.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/bar_graph.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/bar_graph.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4cd9bae3cd26be3d91d5e967053c30920cf9bbe6
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/bar_graph.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/big_text.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/big_text.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0469c488f97958ccf72a8c84afc2168b271887a3
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/big_text.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/box_adapter.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/box_adapter.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bd6f623f96d1382abe945c7b62e74d2ae6a2fa4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/box_adapter.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/columns.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/columns.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..103511eed6cd0734325b8234271f297fdb53e60c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/columns.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/constants.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/constants.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71e772ca43b47b5e779d10887de0d213c0596a9f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/constants.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/container.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/container.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f52c5d1faf2bb1fe63495cd5423db9970ad07d7c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/container.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/divider.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/divider.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..03d94f28b20024af010d100403a6140174a12682
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/divider.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/edit.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/edit.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a418988c0a876c806a7065efb6ad267fc708bea4
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/edit.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/filler.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/filler.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cab495eab99cbdce2bb2514e90be9a3cde25c23c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/filler.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/frame.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/frame.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1790bf4673490124de6aa0f9ed6457fac41955cb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/frame.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/grid_flow.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/grid_flow.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cce9840fc06c9ded5543cef34faa8d113c0c9558
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/grid_flow.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/line_box.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/line_box.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5ea580fec5f7863c7288f914856d38369548d9f
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/line_box.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/listbox.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/listbox.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87373789d2ec9ea1e6602c73a574e1e4d702a3ad
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/listbox.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/monitored_list.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/monitored_list.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95aea41ffe89f8ea55e6935360d2a063f61ecf3a
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/monitored_list.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/overlay.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/overlay.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dc3e5ad749ef44e5eee9bb69a4a4d1c5330ccdb
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/overlay.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/padding.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/padding.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83436a2b75a672407ad5f9881dda2c088a98c9e5
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/padding.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/pile.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/pile.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43a94b038c1c8e29841bb8c6a02a7ce306e62220
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/pile.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/popup.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/popup.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52ea0222cce4f84915eba62ffd909dc22aab9fa1
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/popup.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/progress_bar.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/progress_bar.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02490042edcef69d8bf7dc32ffb53e37b7eed415
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/progress_bar.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/scrollable.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/scrollable.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7474401058deb13b54681acabd265fa5ef42199c
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/scrollable.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/solid_fill.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/solid_fill.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c49b5283661b0956473e16980a969b7019fee1dc
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/solid_fill.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/text.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/text.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de9f5ff8794c420d33067536f3f871150b72db00
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/text.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/treetools.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/treetools.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e42ab3b69e6b2ed394188d14e1579c478b9a618d
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/treetools.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..759c1f0b48075ab40c4f8e2dc77f610cd0a29d88
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget_decoration.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget_decoration.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e478933fdafce1071fe89ef44f617e624b94138
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/widget_decoration.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/wimp.cpython-313.pyc b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/wimp.cpython-313.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb7480815712896f4392c3a88440c2253e11bee
Binary files /dev/null and b/python/user_packages/Python313/site-packages/urwid/widget/__pycache__/wimp.cpython-313.pyc differ
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/attr_map.py b/python/user_packages/Python313/site-packages/urwid/widget/attr_map.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed7ee086bcff9c478969994a13f05cf0ab0331c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/attr_map.py
@@ -0,0 +1,161 @@
+from __future__ import annotations
+
+import typing
+from collections.abc import Hashable, Mapping
+
+from urwid.canvas import CompositeCanvas
+
+from .widget import WidgetError, delegate_to_widget_mixin
+from .widget_decoration import WidgetDecoration
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class AttrMapError(WidgetError):
+    pass
+
+
+class AttrMap(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]):
+    """
+    AttrMap is a decoration that maps one set of attributes to another.
+    This object will pass all function calls and variable references to the
+    wrapped widget.
+    """
+
+    def __init__(
+        self,
+        w: WrappedWidget,
+        attr_map: Hashable | Mapping[Hashable | None, Hashable] | None,
+        focus_map: Hashable | Mapping[Hashable | None, Hashable] | None = None,
+    ) -> None:
+        """
+        :param w: widget to wrap (stored as self.original_widget)
+        :type w: widget
+
+        :param attr_map: attribute to apply to *w*, or dict of old display
+            attribute: new display attribute mappings
+        :type attr_map: display attribute or dict
+
+        :param focus_map: attribute to apply when in focus or dict of
+            old display attribute: new display attribute mappings;
+            if ``None`` use *attr*
+        :type focus_map: display attribute or dict
+
+        >>> from urwid import Divider, Edit, Text
+        >>> AttrMap(Divider("!"), "bright")
+         attr_map={None: 'bright'}>
+        >>> AttrMap(Edit(), "notfocus", "focus").attr_map
+        {None: 'notfocus'}
+        >>> AttrMap(Edit(), "notfocus", "focus").focus_map
+        {None: 'focus'}
+        >>> size = (5,)
+        >>> am = AttrMap(Text("hi"), "greeting", "fgreet")
+        >>> next(am.render(size, focus=False).content())  # ... = b in Python 3
+        [('greeting', None, ...'hi   ')]
+        >>> next(am.render(size, focus=True).content())
+        [('fgreet', None, ...'hi   ')]
+        >>> am2 = AttrMap(Text(("word", "hi")), {"word": "greeting", None: "bg"})
+        >>> am2
+         attr_map={'word': 'greeting', None: 'bg'}>
+        >>> next(am2.render(size).content())
+        [('greeting', None, ...'hi'), ('bg', None, ...'   ')]
+        """
+        super().__init__(w)
+
+        if isinstance(attr_map, Mapping):
+            self.attr_map = dict(attr_map)
+        else:
+            self.attr_map = {None: attr_map}
+
+        if isinstance(focus_map, Mapping):
+            self.focus_map = dict(focus_map)
+        elif focus_map is None:
+            self.focus_map = focus_map
+        else:
+            self.focus_map = {None: focus_map}
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        # only include the focus_attr when it takes effect (not None)
+        d = {**super()._repr_attrs(), "attr_map": self._attr_map}
+        if self._focus_map is not None:
+            d["focus_map"] = self._focus_map
+        return d
+
+    def get_attr_map(self) -> dict[Hashable | None, Hashable]:
+        # make a copy so ours is not accidentally modified
+        # FIXME: a dictionary that detects modifications would be better
+        return dict(self._attr_map)
+
+    def set_attr_map(self, attr_map: dict[Hashable | None, Hashable] | None) -> None:
+        """
+        Set the attribute mapping dictionary {from_attr: to_attr, ...}
+
+        Note this function does not accept a single attribute the way the
+        constructor does.  You must specify {None: attribute} instead.
+
+        >>> from urwid import Text
+        >>> w = AttrMap(Text("hi"), None)
+        >>> w.set_attr_map({"a": "b"})
+        >>> w
+         attr_map={'a': 'b'}>
+        """
+        for from_attr, to_attr in attr_map.items():
+            if not isinstance(from_attr, Hashable) or not isinstance(to_attr, Hashable):
+                raise AttrMapError(
+                    f"{from_attr!r}:{to_attr!r} attribute mapping is invalid. Attributes must be hashable"
+                )
+
+        self._attr_map = attr_map
+        self._invalidate()
+
+    attr_map = property(get_attr_map, set_attr_map)
+
+    def get_focus_map(self) -> dict[Hashable | None, Hashable] | None:
+        # make a copy so ours is not accidentally modified
+        # FIXME: a dictionary that detects modifications would be better
+        if self._focus_map:
+            return dict(self._focus_map)
+        return None
+
+    def set_focus_map(self, focus_map: dict[Hashable | None, Hashable] | None) -> None:
+        """
+        Set the focus attribute mapping dictionary
+        {from_attr: to_attr, ...}
+
+        If None this widget will use the attr mapping instead (no change
+        when in focus).
+
+        Note this function does not accept a single attribute the way the
+        constructor does.  You must specify {None: attribute} instead.
+
+        >>> from urwid import Text
+        >>> w = AttrMap(Text("hi"), {})
+        >>> w.set_focus_map({"a": "b"})
+        >>> w
+         attr_map={} focus_map={'a': 'b'}>
+        >>> w.set_focus_map(None)
+        >>> w
+         attr_map={}>
+        """
+        if focus_map is not None:
+            for from_attr, to_attr in focus_map.items():
+                if not isinstance(from_attr, Hashable) or not isinstance(to_attr, Hashable):
+                    raise AttrMapError(
+                        f"{from_attr!r}:{to_attr!r} attribute mapping is invalid. Attributes must be hashable"
+                    )
+        self._focus_map = focus_map
+        self._invalidate()
+
+    focus_map = property(get_focus_map, set_focus_map)
+
+    def render(self, size, focus: bool = False) -> CompositeCanvas:
+        """
+        Render wrapped widget and apply attribute. Return canvas.
+        """
+        attr_map = self._attr_map
+        if focus and self._focus_map is not None:
+            attr_map = self._focus_map
+        canv = self._original_widget.render(size, focus=focus)
+        canv = CompositeCanvas(canv)
+        canv.fill_attr_apply(attr_map)
+        return canv
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/attr_wrap.py b/python/user_packages/Python313/site-packages/urwid/widget/attr_wrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..897793a136301e239cab82e3c161237d606040a5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/attr_wrap.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from .attr_map import AttrMap
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable
+
+    from .constants import Sizing
+    from .widget import Widget
+
+
+class AttrWrap(AttrMap):
+    def __init__(self, w: Widget, attr, focus_attr=None):
+        """
+        w -- widget to wrap (stored as self.original_widget)
+        attr -- attribute to apply to w
+        focus_attr -- attribute to apply when in focus, if None use attr
+
+        This widget is a special case of the new AttrMap widget, and it
+        will pass all function calls and variable references to the wrapped
+        widget.  This class is maintained for backwards compatibility only,
+        new code should use AttrMap instead.
+
+        >>> from urwid import Divider, Edit, Text
+        >>> AttrWrap(Divider("!"), "bright")
+         attr='bright'>
+        >>> AttrWrap(Edit(), "notfocus", "focus")
+         attr='notfocus' focus_attr='focus'>
+        >>> size = (5,)
+        >>> aw = AttrWrap(Text("hi"), "greeting", "fgreet")
+        >>> next(aw.render(size, focus=False).content())
+        [('greeting', None, ...'hi   ')]
+        >>> next(aw.render(size, focus=True).content())
+        [('fgreet', None, ...'hi   ')]
+        """
+        warnings.warn(
+            "AttrWrap is maintained for backwards compatibility only, new code should use AttrMap instead.",
+            PendingDeprecationWarning,
+            stacklevel=2,
+        )
+        super().__init__(w, attr, focus_attr)
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        # only include the focus_attr when it takes effect (not None)
+        d = {**super()._repr_attrs(), "attr": self.attr}
+        del d["attr_map"]
+        d.pop("focus_map", None)
+        if self.focus_attr is not None:
+            d["focus_attr"] = self.focus_attr
+        return d
+
+    @property
+    def w(self) -> Widget:
+        """backwards compatibility, widget used to be stored as w"""
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as original_widget. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.original_widget
+
+    @w.setter
+    def w(self, new_widget: Widget) -> None:
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as original_widget. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.original_widget = new_widget
+
+    def get_w(self):
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as original_widget. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.original_widget
+
+    def set_w(self, new_widget: Widget) -> None:
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as original_widget. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.original_widget = new_widget
+
+    def get_attr(self) -> Hashable:
+        return self.attr_map[None]
+
+    def set_attr(self, attr: Hashable) -> None:
+        """
+        Set the attribute to apply to the wrapped widget
+
+        >> w = AttrWrap(Divider("-"), None)
+        >> w.set_attr('new_attr')
+        >> w
+         attr='new_attr'>
+        """
+        self.set_attr_map({None: attr})
+
+    attr = property(get_attr, set_attr)
+
+    def get_focus_attr(self) -> Hashable | None:
+        if focus_map := self.focus_map:
+            return focus_map[None]
+        return None
+
+    def set_focus_attr(self, focus_attr: Hashable) -> None:
+        """
+        Set the attribute to apply to the wapped widget when it is in
+        focus
+
+        If None this widget will use the attr instead (no change when in
+        focus).
+
+        >> w = AttrWrap(Divider("-"), 'old')
+        >> w.set_focus_attr('new_attr')
+        >> w
+         attr='old' focus_attr='new_attr'>
+        >> w.set_focus_attr(None)
+        >> w
+         attr='old'>
+        """
+        self.set_focus_map({None: focus_attr})
+
+    focus_attr = property(get_focus_attr, set_focus_attr)
+
+    def __getattr__(self, name: str):
+        """
+        Call getattr on wrapped widget.  This has been the longstanding
+        behaviour of AttrWrap, but is discouraged.  New code should be
+        using AttrMap and .base_widget or .original_widget instead.
+        """
+        return getattr(self._original_widget, name)
+
+    def sizing(self) -> frozenset[Sizing]:
+        return self._original_widget.sizing()
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/bar_graph.py b/python/user_packages/Python313/site-packages/urwid/widget/bar_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..818e1a901af7c1115d598f69b49dfd38f21e26cf
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/bar_graph.py
@@ -0,0 +1,648 @@
+from __future__ import annotations
+
+import typing
+
+from urwid.canvas import CanvasCombine, CompositeCanvas, SolidCanvas
+from urwid.util import get_encoding_mode
+
+from .constants import BAR_SYMBOLS, Sizing
+from .text import Text
+from .widget import Widget, WidgetError, WidgetMeta, nocache_widget_render, nocache_widget_render_instance
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+
+class BarGraphMeta(WidgetMeta):
+    """
+    Detect subclass get_data() method and dynamic change to
+    get_data() method and disable caching in these cases.
+
+    This is for backwards compatibility only, new programs
+    should use set_data() instead of overriding get_data().
+    """
+
+    def __init__(cls, name, bases, d):
+        # pylint: disable=protected-access
+
+        super().__init__(name, bases, d)
+
+        if "get_data" in d:
+            cls.render = nocache_widget_render(cls)
+            cls._get_data = cls.get_data
+        cls.get_data = property(lambda self: self._get_data, nocache_bargraph_get_data)
+
+
+def nocache_bargraph_get_data(self, get_data_fn):
+    """
+    Disable caching on this bargraph because get_data_fn needs
+    to be polled to get the latest data.
+    """
+    self.render = nocache_widget_render_instance(self)
+    self._get_data = get_data_fn  # pylint: disable=protected-access
+
+
+class BarGraphError(WidgetError):
+    pass
+
+
+class BarGraph(Widget, metaclass=BarGraphMeta):
+    _sizing = frozenset([Sizing.BOX])
+
+    ignore_focus = True
+
+    eighths = BAR_SYMBOLS.VERTICAL[:8]  # Full height is done by style
+    hlines = "_⎺⎻─⎼⎽"
+
+    def __init__(self, attlist, hatt=None, satt=None) -> None:
+        """
+        Create a bar graph with the passed display characteristics.
+        see set_segment_attributes for a description of the parameters.
+        """
+        super().__init__()
+        self.set_segment_attributes(attlist, hatt, satt)
+        self.set_data([], 1, None)
+        self.set_bar_width(None)
+
+    def set_segment_attributes(self, attlist, hatt=None, satt=None):
+        """
+        :param attlist: list containing display attribute or
+                        (display attribute, character) tuple for background,
+                        first segment, and optionally following segments.
+                        ie. len(attlist) == num segments+1
+                        character defaults to ' ' if not specified.
+        :param hatt: list containing attributes for horizontal lines. First
+                     element is for lines on background, second is for lines
+                     on first segment, third is for lines on second segment
+                     etc.
+        :param satt: dictionary containing attributes for smoothed
+                     transitions of bars in UTF-8 display mode. The values
+                     are in the form:
+
+                       (fg,bg) : attr
+
+                     fg and bg are integers where 0 is the graph background,
+                     1 is the first segment, 2 is the second, ...
+                     fg > bg in all values.  attr is an attribute with a
+                     foreground corresponding to fg and a background
+                     corresponding to bg.
+
+        If satt is not None and the bar graph is being displayed in
+        a terminal using the UTF-8 encoding then the character cell
+        that is shared between the segments specified will be smoothed
+        with using the UTF-8 vertical eighth characters.
+
+        eg: set_segment_attributes( ['no', ('unsure',"?"), 'yes'] )
+        will use the attribute 'no' for the background (the area from
+        the top of the graph to the top of the bar), question marks
+        with the attribute 'unsure' will be used for the topmost
+        segment of the bar, and the attribute 'yes' will be used for
+        the bottom segment of the bar.
+        """
+        self.attr = []
+        self.char = []
+        if len(attlist) < 2:
+            raise BarGraphError(f"attlist must include at least background and seg1: {attlist!r}")
+        if len(attlist) < 2:
+            raise BarGraphError("must at least specify bg and fg!")
+        for a in attlist:
+            if not isinstance(a, tuple):
+                self.attr.append(a)
+                self.char.append(" ")
+            else:
+                attr, ch = a
+                self.attr.append(attr)
+                self.char.append(ch)
+
+        self.hatt = []
+        if hatt is None:
+            hatt = [self.attr[0]]
+        elif not isinstance(hatt, list):
+            hatt = [hatt]
+        self.hatt = hatt
+
+        if satt is None:
+            satt = {}
+        for i in satt.items():
+            try:
+                (fg, bg), attr = i
+            except ValueError as exc:
+                raise BarGraphError(f"satt not in (fg,bg:attr) form: {i!r}").with_traceback(exc.__traceback__) from exc
+            if not isinstance(fg, int) or fg >= len(attlist):
+                raise BarGraphError(f"fg not valid integer: {fg!r}")
+            if not isinstance(bg, int) or bg >= len(attlist):
+                raise BarGraphError(f"bg not valid integer: {fg!r}")
+            if fg <= bg:
+                raise BarGraphError(f"fg ({fg}) not > bg ({bg})")
+        self.satt = satt
+
+    def set_data(self, bardata, top: float, hlines=None) -> None:
+        """
+        Store bar data, bargraph top and horizontal line positions.
+
+        bardata -- a list of bar values.
+        top -- maximum value for segments within bardata
+        hlines -- None or a bar value marking horizontal line positions
+
+        bar values are [ segment1, segment2, ... ] lists where top is
+        the maximal value corresponding to the top of the bar graph and
+        segment1, segment2, ... are the values for the top of each
+        segment of this bar.  Simple bar graphs will only have one
+        segment in each bar value.
+
+        Eg: if top is 100 and there is a bar value of [ 80, 30 ] then
+        the top of this bar will be at 80% of full height of the graph
+        and it will have a second segment that starts at 30%.
+        """
+        if hlines is not None:
+            hlines = sorted(hlines[:], reverse=True)  # shallow copy
+
+        self.data = bardata, top, hlines
+        self._invalidate()
+
+    def _get_data(self, size: tuple[int, int]):
+        """
+        Return (bardata, top, hlines)
+
+        This function is called by render to retrieve the data for
+        the graph. It may be overloaded to create a dynamic bar graph.
+
+        This implementation will truncate the bardata list returned
+        if not all bars will fit within maxcol.
+        """
+        (maxcol, maxrow) = size
+        bardata, top, hlines = self.data
+        widths = self.calculate_bar_widths((maxcol, maxrow), bardata)
+
+        if len(bardata) > len(widths):
+            return bardata[: len(widths)], top, hlines
+
+        return bardata, top, hlines
+
+    def set_bar_width(self, width: int | None):
+        """
+        Set a preferred bar width for calculate_bar_widths to use.
+
+        width -- width of bar or None for automatic width adjustment
+        """
+        if width is not None and width <= 0:
+            raise ValueError(width)
+        self.bar_width = width
+        self._invalidate()
+
+    def calculate_bar_widths(self, size: tuple[int, int], bardata):
+        """
+        Return a list of bar widths, one for each bar in data.
+
+        If self.bar_width is None this implementation will stretch
+        the bars across the available space specified by maxcol.
+        """
+        (maxcol, _maxrow) = size
+
+        if self.bar_width is not None:
+            return [self.bar_width] * min(len(bardata), maxcol // self.bar_width)
+
+        if len(bardata) >= maxcol:
+            return [1] * maxcol
+
+        widths = []
+        grow = maxcol
+        remain = len(bardata)
+        for _row in bardata:
+            w = int(float(grow) / remain + 0.5)
+            widths.append(w)
+            grow -= w
+            remain -= 1
+        return widths
+
+    def selectable(self) -> Literal[False]:
+        """
+        Return False.
+        """
+        return False
+
+    def use_smoothed(self) -> bool:
+        return self.satt and get_encoding_mode() == "utf8"
+
+    def calculate_display(self, size: tuple[int, int]):
+        """
+        Calculate display data.
+        """
+        (maxcol, maxrow) = size
+        bardata, top, hlines = self.get_data((maxcol, maxrow))  # pylint: disable=no-member  # metaclass defined
+        widths = self.calculate_bar_widths((maxcol, maxrow), bardata)
+
+        if self.use_smoothed():
+            disp = calculate_bargraph_display(bardata, top, widths, maxrow * 8)
+            disp = self.smooth_display(disp)
+
+        else:
+            disp = calculate_bargraph_display(bardata, top, widths, maxrow)
+
+        if hlines:
+            disp = self.hlines_display(disp, top, hlines, maxrow)
+
+        return disp
+
+    def hlines_display(self, disp, top: int, hlines, maxrow: int):
+        """
+        Add hlines to display structure represented as bar_type tuple
+        values:
+        (bg, 0-5)
+        bg is the segment that has the hline on it
+        0-5 is the hline graphic to use where 0 is a regular underscore
+        and 1-5 are the UTF-8 horizontal scan line characters.
+        """
+        if self.use_smoothed():
+            shiftr = 0
+            r = [
+                (0.2, 1),
+                (0.4, 2),
+                (0.6, 3),
+                (0.8, 4),
+                (1.0, 5),
+            ]
+        else:
+            shiftr = 0.5
+            r = [
+                (1.0, 0),
+            ]
+
+        # reverse the hlines to match screen ordering
+        rhl = [rh for h in hlines if (rh := float(top - h) * maxrow / top - shiftr) >= 0]
+
+        # build a list of rows that will have hlines
+        hrows = []
+        last_i = -1
+        for rh in rhl:
+            i = int(rh)
+            if i == last_i:
+                continue
+            f = rh - i
+            for spl, chnum in r:
+                if f < spl:
+                    hrows.append((i, chnum))
+                    break
+            last_i = i
+
+        # fill hlines into disp data
+        def fill_row(row, chnum):
+            rout = []
+            for bar_type, width in row:
+                if isinstance(bar_type, int) and len(self.hatt) > bar_type:
+                    rout.append(((bar_type, chnum), width))
+                    continue
+                rout.append((bar_type, width))
+            return rout
+
+        o = []
+        k = 0
+        rnum = 0
+        for y_count, row in disp:
+            if k >= len(hrows):
+                o.append((y_count, row))
+                continue
+            end_block = rnum + y_count
+            while k < len(hrows) and hrows[k][0] < end_block:
+                i, chnum = hrows[k]
+                if i - rnum > 0:
+                    o.append((i - rnum, row))
+                o.append((1, fill_row(row, chnum)))
+                rnum = i + 1
+                k += 1
+            if rnum < end_block:
+                o.append((end_block - rnum, row))
+                rnum = end_block
+
+        # assert 0, o
+        return o
+
+    def smooth_display(self, disp):
+        """
+        smooth (col, row*8) display into (col, row) display using
+        UTF vertical eighth characters represented as bar_type
+        tuple values:
+        ( fg, bg, 1-7 )
+        where fg is the lower segment, bg is the upper segment and
+        1-7 is the vertical eighth character to use.
+        """
+        o = []
+        r = 0  # row remainder
+
+        def seg_combine(a, b):
+            (bt1, w1), (bt2, w2) = a, b
+            if (bt1, w1) == (bt2, w2):
+                return (bt1, w1), None, None
+            wmin = min(w1, w2)
+            l1 = l2 = None
+            if w1 > w2:
+                l1 = (bt1, w1 - w2)
+            elif w2 > w1:
+                l2 = (bt2, w2 - w1)
+            if isinstance(bt1, tuple):
+                return (bt1, wmin), l1, l2
+            if (bt2, bt1) not in self.satt:
+                if r < 4:
+                    return (bt2, wmin), l1, l2
+                return (bt1, wmin), l1, l2
+            return ((bt2, bt1, 8 - r), wmin), l1, l2
+
+        def row_combine_last(count: int, row):
+            o_count, o_row = o[-1]
+            row = row[:]  # shallow copy, so we don't destroy orig.
+            o_row = o_row[:]
+            widget_list = []
+            while row:
+                (bt, w), l1, l2 = seg_combine(o_row.pop(0), row.pop(0))
+                if widget_list and widget_list[-1][0] == bt:
+                    widget_list[-1] = (bt, widget_list[-1][1] + w)
+                else:
+                    widget_list.append((bt, w))
+                if l1:
+                    o_row = [l1, *o_row]
+                if l2:
+                    row = [l2, *row]
+
+            if o_row:
+                raise BarGraphError(o_row)
+
+            o[-1] = (o_count + count, widget_list)
+
+        # regroup into actual rows (8 disp rows == 1 actual row)
+        for y_count, row in disp:
+            if r:
+                count = min(8 - r, y_count)
+                row_combine_last(count, row)
+                y_count -= count  # noqa: PLW2901
+                r += count
+                r %= 8
+                if not y_count:
+                    continue
+            if r != 0:
+                raise BarGraphError
+            # copy whole blocks
+            if y_count > 7:
+                o.append((y_count // 8 * 8, row))
+                y_count %= 8  # noqa: PLW2901
+                if not y_count:
+                    continue
+            o.append((y_count, row))
+            r = y_count
+        return [(y // 8, row) for (y, row) in o]
+
+    def render(self, size: tuple[int, int], focus: bool = False) -> CompositeCanvas:
+        """
+        Render BarGraph.
+        """
+        (maxcol, maxrow) = size
+        disp = self.calculate_display((maxcol, maxrow))
+
+        combinelist = []
+        for y_count, row in disp:
+            widget_list = []
+            for bar_type, width in row:
+                if isinstance(bar_type, tuple):
+                    if len(bar_type) == 3:
+                        # vertical eighths
+                        fg, bg, k = bar_type
+                        a = self.satt[fg, bg]
+                        t = self.eighths[k] * width
+                    else:
+                        # horizontal lines
+                        bg, k = bar_type
+                        a = self.hatt[bg]
+                        t = self.hlines[k] * width
+                else:
+                    a = self.attr[bar_type]
+                    t = self.char[bar_type] * width
+                widget_list.append((a, t))
+            c = Text(widget_list).render((maxcol,))
+            if c.rows() != 1:
+                raise BarGraphError("Invalid characters in BarGraph!")
+            combinelist += [(c, None, False)] * y_count
+
+        canv = CanvasCombine(combinelist)
+        return canv
+
+
+def calculate_bargraph_display(bardata, top: float, bar_widths: list[int], maxrow: int):
+    """
+    Calculate a rendering of the bar graph described by data, bar_widths
+    and height.
+
+    bardata -- bar information with same structure as BarGraph.data
+    top -- maximal value for bardata segments
+    bar_widths -- list of integer column widths for each bar
+    maxrow -- rows for display of bargraph
+
+    Returns a structure as follows:
+      [ ( y_count, [ ( bar_type, width), ... ] ), ... ]
+
+    The outer tuples represent a set of identical rows. y_count is
+    the number of rows in this set, the list contains the data to be
+    displayed in the row repeated through the set.
+
+    The inner tuple describes a run of width characters of bar_type.
+    bar_type is an integer starting from 0 for the background, 1 for
+    the 1st segment, 2 for the 2nd segment etc..
+
+    This function should complete in approximately O(n+m) time, where
+    n is the number of bars displayed and m is the number of rows.
+    """
+
+    if len(bardata) != len(bar_widths):
+        raise BarGraphError
+
+    maxcol = sum(bar_widths)
+
+    # build intermediate data structure
+    rows = [None] * maxrow
+
+    def add_segment(seg_num: int, col: int, row: int, width: int, rows=rows) -> None:
+        if rows[row]:
+            last_seg, last_col, last_end = rows[row][-1]
+            if last_end > col:
+                if last_col >= col:
+                    del rows[row][-1]
+                else:
+                    rows[row][-1] = (last_seg, last_col, col)
+            elif last_seg == seg_num and last_end == col:
+                rows[row][-1] = (last_seg, last_col, last_end + width)
+                return
+        elif rows[row] is None:
+            rows[row] = []
+        rows[row].append((seg_num, col, col + width))
+
+    col = 0
+    barnum = 0
+    for bar in bardata:
+        width = bar_widths[barnum]
+        if width < 1:
+            continue
+        # loop through in reverse order
+        tallest = maxrow
+        segments = scale_bar_values(bar, top, maxrow)
+        for k in range(len(bar) - 1, -1, -1):
+            s = segments[k]
+
+            if s >= maxrow:
+                continue
+            s = max(s, 0)
+            if s < tallest:
+                # add only properly-overlapped bars
+                tallest = s
+                add_segment(k + 1, col, s, width)
+        col += width
+        barnum += 1
+
+    # print(repr(rows))
+    # build rowsets data structure
+    rowsets = []
+    y_count = 0
+    last = [(0, maxcol)]
+
+    for r in rows:
+        if r is None:
+            y_count += 1
+            continue
+        if y_count:
+            rowsets.append((y_count, last))
+            y_count = 0
+
+        i = 0  # index into "last"
+        la, ln = last[i]  # last attribute, last run length
+        c = 0  # current column
+        o = []  # output list to be added to rowsets
+        for seg_num, start, end in r:
+            while start > c + ln:
+                o.append((la, ln))
+                i += 1
+                c += ln
+                la, ln = last[i]
+
+            if la == seg_num:
+                # same attribute, can combine
+                o.append((la, end - c))
+            else:
+                if start - c > 0:
+                    o.append((la, start - c))
+                o.append((seg_num, end - start))
+
+            if end == maxcol:
+                i = len(last)
+                break
+
+            # skip past old segments covered by new one
+            while end >= c + ln:
+                i += 1
+                c += ln
+                la, ln = last[i]
+
+            if la != seg_num:
+                ln = c + ln - end
+                c = end
+                continue
+
+            # same attribute, can extend
+            oa, on = o[-1]
+            on += c + ln - end
+            o[-1] = oa, on
+
+            i += 1
+            c += ln
+            if c == maxcol:
+                break
+            if i >= len(last):
+                raise ValueError(repr((on, maxcol)))
+            la, ln = last[i]
+
+        if i < len(last):
+            o += [(la, ln), *last[i + 1 :]]
+        last = o
+        y_count += 1
+
+    if y_count:
+        rowsets.append((y_count, last))
+
+    return rowsets
+
+
+class GraphVScale(Widget):
+    _sizing = frozenset([Sizing.BOX])
+
+    def __init__(self, labels, top: float) -> None:
+        """
+        GraphVScale( [(label1 position, label1 markup),...], top )
+        label position -- 0 < position < top for the y position
+        label markup -- text markup for this label
+        top -- top y position
+
+        This widget is a vertical scale for the BarGraph widget that
+        can correspond to the BarGraph's horizontal lines
+        """
+        super().__init__()
+        self.set_scale(labels, top)
+
+    def set_scale(self, labels, top: float) -> None:
+        """
+        set_scale( [(label1 position, label1 markup),...], top )
+        label position -- 0 < position < top for the y position
+        label markup -- text markup for this label
+        top -- top y position
+        """
+
+        labels = sorted(labels[:], reverse=True)  # shallow copy
+
+        self.pos = []
+        self.txt = []
+        for y, markup in labels:
+            self.pos.append(y)
+            self.txt.append(Text(markup))
+        self.top = top
+
+    def selectable(self) -> Literal[False]:
+        """
+        Return False.
+        """
+        return False
+
+    def render(
+        self,
+        size: tuple[int, int],
+        focus: bool = False,
+    ) -> SolidCanvas | CompositeCanvas:
+        """
+        Render GraphVScale.
+        """
+        (maxcol, maxrow) = size
+        pl = scale_bar_values(self.pos, self.top, maxrow)
+
+        combinelist = []
+        rows = 0
+        for p, t in zip(pl, self.txt):
+            p -= 1  # noqa: PLW2901
+            if p >= maxrow:
+                break
+            if p < rows:
+                continue
+            c = t.render((maxcol,))
+            if p > rows:
+                run = p - rows
+                c = CompositeCanvas(c)
+                c.pad_trim_top_bottom(run, 0)
+            rows += c.rows()
+            combinelist.append((c, None, False))
+        if not combinelist:
+            return SolidCanvas(" ", size[0], size[1])
+
+        canvas = CanvasCombine(combinelist)
+        if maxrow - rows:
+            canvas.pad_trim_top_bottom(0, maxrow - rows)
+        return canvas
+
+
+def scale_bar_values(bar, top: float, maxrow: int) -> list[int]:
+    """
+    Return a list of bar values aliased to integer values of maxrow.
+    """
+    return [maxrow - int(float(v) * maxrow / top + 0.5) for v in bar]
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/big_text.py b/python/user_packages/Python313/site-packages/urwid/widget/big_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..b880e1a78bf48a23b00c54dc7e305e41f6b0e344
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/big_text.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import typing
+
+from urwid.canvas import CanvasJoin, CompositeCanvas, TextCanvas
+from urwid.util import decompose_tagmarkup
+
+from .constants import Sizing
+from .widget import Widget, fixed_size
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable
+
+    from urwid import Font
+
+
+class BigText(Widget):
+    _sizing = frozenset([Sizing.FIXED])
+
+    def __init__(self, markup, font: Font) -> None:
+        """
+        markup -- same as Text widget markup
+        font -- instance of a Font class
+        """
+        super().__init__()
+        self.text: str = ""
+        self.attrib = []
+        self.font: Font = font
+        self.set_font(font)
+        self.set_text(markup)
+
+    def set_text(self, markup):
+        self.text, self.attrib = decompose_tagmarkup(markup)
+        self._invalidate()
+
+    def get_text(self):
+        """
+        Returns (text, attributes).
+        """
+        return self.text, self.attrib
+
+    def set_font(self, font: Font) -> None:
+        self.font = font
+        self._invalidate()
+
+    def pack(
+        self,
+        size: tuple[()] | None = (),  # type: ignore[override]
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        rows = self.font.height
+        cols = 0
+        for c in self.text:
+            cols += self.font.char_width(c)
+        return cols, rows
+
+    def render(
+        self,
+        size: tuple[()],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        fixed_size(size)  # complain if parameter is wrong
+        a: Hashable | None = None
+        ai = ak = 0
+        o = []
+        rows = self.font.height
+        attrib = [*self.attrib, (None, len(self.text))]
+        for ch in self.text:
+            if not ak:
+                a, ak = attrib[ai]
+                ai += 1
+            ak -= 1
+
+            if width := self.font.char_width(ch):
+                c: TextCanvas | CompositeCanvas = self.font.render(ch)
+                if a is not None:
+                    c = CompositeCanvas(c)
+                    c.fill_attr(a)
+                o.append((c, None, False, width))
+
+        if o:
+            canv = CanvasJoin(o)
+        else:
+            canv = CompositeCanvas(TextCanvas([b""] * rows, maxcol=0, check_width=False))
+        canv.set_depends([])
+        return canv
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/box_adapter.py b/python/user_packages/Python313/site-packages/urwid/widget/box_adapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca949ca2dd919534ff0da5b9b013bfb053c1755e
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/box_adapter.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from urwid.canvas import CompositeCanvas
+
+from .constants import Sizing
+from .widget_decoration import WidgetDecoration, WidgetError
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class BoxAdapterError(WidgetError):
+    pass
+
+
+class BoxAdapter(WidgetDecoration[WrappedWidget]):
+    """
+    Adapter for using a box widget where a flow widget would usually go
+    """
+
+    no_cache: typing.ClassVar[list[str]] = ["rows"]
+
+    def __init__(self, box_widget: WrappedWidget, height: int) -> None:
+        """
+        Create a flow widget that contains a box widget
+
+        :param box_widget: box widget to wrap
+        :type box_widget: Widget
+        :param height: number of rows for box widget
+        :type height: int
+
+        >>> from urwid import SolidFill
+        >>> BoxAdapter(SolidFill("x"), 5)  # 5-rows of x's
+         height=5>
+        """
+        if hasattr(box_widget, "sizing") and Sizing.BOX not in box_widget.sizing():
+            raise BoxAdapterError(f"{box_widget!r} is not a box widget")
+        super().__init__(box_widget)
+
+        self.height = height
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        return {**super()._repr_attrs(), "height": self.height}
+
+    # originally stored as box_widget, keep for compatibility
+    @property
+    def box_widget(self) -> WrappedWidget:
+        warnings.warn(
+            "original stored as original_widget, keep for compatibility. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.original_widget
+
+    @box_widget.setter
+    def box_widget(self, widget: WrappedWidget) -> None:
+        warnings.warn(
+            "original stored as original_widget, keep for compatibility. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.original_widget = widget
+
+    def sizing(self) -> frozenset[Sizing]:
+        return frozenset((Sizing.FLOW,))
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """
+        Return the predetermined height (behave like a flow widget)
+
+        >>> from urwid import SolidFill
+        >>> BoxAdapter(SolidFill("x"), 5).rows((20,))
+        5
+        """
+        return self.height
+
+    # The next few functions simply tack-on our height and pass through
+    # to self._original_widget
+    def get_cursor_coords(self, size: tuple[int]) -> int | None:
+        (maxcol,) = size
+        if not hasattr(self._original_widget, "get_cursor_coords"):
+            return None
+        return self._original_widget.get_cursor_coords((maxcol, self.height))
+
+    def get_pref_col(self, size: tuple[int]) -> int | None:
+        (maxcol,) = size
+        if not hasattr(self._original_widget, "get_pref_col"):
+            return None
+        return self._original_widget.get_pref_col((maxcol, self.height))
+
+    def keypress(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        (maxcol,) = size
+        return self._original_widget.keypress((maxcol, self.height), key)
+
+    def move_cursor_to_coords(self, size: tuple[int], col: int, row: int):
+        (maxcol,) = size
+        if not hasattr(self._original_widget, "move_cursor_to_coords"):
+            return True
+        return self._original_widget.move_cursor_to_coords((maxcol, self.height), col, row)
+
+    def mouse_event(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        (maxcol,) = size
+        if not hasattr(self._original_widget, "mouse_event"):
+            return False
+        return self._original_widget.mouse_event((maxcol, self.height), event, button, col, row, focus)
+
+    def render(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        (maxcol,) = size
+        canv = CompositeCanvas(self._original_widget.render((maxcol, self.height), focus))
+        return canv
+
+    def __getattr__(self, name: str):
+        """
+        Pass calls to box widget.
+        """
+        return getattr(self.original_widget, name)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/columns.py b/python/user_packages/Python313/site-packages/urwid/widget/columns.py
new file mode 100644
index 0000000000000000000000000000000000000000..8797ee41032fd50dcf866c78d8c8c1c4753daecb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/columns.py
@@ -0,0 +1,1201 @@
+from __future__ import annotations
+
+import typing
+import warnings
+from itertools import chain, repeat
+
+import urwid
+from urwid.canvas import Canvas, CanvasJoin, CompositeCanvas, SolidCanvas
+from urwid.command_map import Command
+from urwid.split_repr import remove_defaults
+from urwid.util import is_mouse_press
+
+from .constants import Align, Sizing, WHSettings
+from .container import WidgetContainerListContentsMixin, WidgetContainerMixin, _ContainerElementSizingFlag
+from .monitored_list import MonitoredFocusList, MonitoredList
+from .widget import Widget, WidgetError, WidgetWarning
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterable, Iterator, Sequence
+
+    from typing_extensions import Literal
+
+
+class ColumnsError(WidgetError):
+    """Columns related errors."""
+
+
+class ColumnsWarning(WidgetWarning):
+    """Columns related warnings."""
+
+
+class Columns(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin):
+    """
+    Widgets arranged horizontally in columns from left to right
+    """
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Sizing supported by widget.
+
+        :return: Calculated widget sizing
+        :rtype: frozenset[Sizing]
+
+        Due to the nature of container with mutable contents, this method cannot be cached.
+
+        Rules:
+        * WEIGHT BOX -> BOX
+        * GIVEN BOX -> Can be included in FIXED and FLOW depends on the other columns
+        * PACK BOX -> Unsupported
+        * BOX-only widget without `box_columns` disallow FLOW render
+
+        * WEIGHT FLOW -> FLOW
+        * GIVEN FLOW -> FIXED (known width and widget knows its height) + FLOW (historic)
+        * PACK FLOW -> FLOW (widget fit in provided size)
+
+        * WEIGHT FIXED -> Need also FLOW or/and BOX to properly render due to width calculation
+        * GIVEN FIXED -> Unsupported
+        * PACK FIXED -> FIXED (widget knows its size)
+
+        Backward compatibility rules:
+        * GIVEN BOX -> Allow BOX
+
+        BOX can be only if ALL widgets support BOX.
+        FIXED can be only if no BOX without "box_columns" flag and no strict FLOW.
+
+        >>> from urwid import BigText, Edit, SolidFill, Text, Thin3x3Font
+        >>> font = Thin3x3Font()
+
+        # BOX-only widget
+        >>> Columns((SolidFill("#"),))
+        
+
+        # BOX-only widget with "get height from max"
+        >>> Columns((SolidFill("#"),), box_columns=(0,))
+        
+
+        # FLOW-only
+        >>> Columns((Edit(),))
+        
+
+        # FLOW allowed by "box_columns"
+        >>> Columns((Edit(), SolidFill("#")), box_columns=(1,))
+        
+
+        # FLOW/FIXED
+        >>> Columns((Text("T"),))
+        
+
+        # GIVEN BOX only -> BOX only
+        >>> Columns(((5, SolidFill("#")),), box_columns=(0,))
+        
+
+        # No FLOW - BOX only
+        >>> Columns(((5, SolidFill("#")), SolidFill("*")), box_columns=(0, 1))
+        
+
+        # FIXED only -> FIXED (and FLOW via drop/expand)
+        >>> Columns(((WHSettings.PACK, BigText("1", font)),))
+        
+
+        # Invalid sizing combination -> use fallback settings (and produce warning)
+        >>> Columns(((WHSettings.PACK, SolidFill("#")),))
+        
+
+        # Special case: empty columns widget sizing is impossible to calculate
+        >>> Columns(())
+        
+        """
+        if not self.contents:
+            return frozenset((urwid.BOX, urwid.FLOW))
+
+        strict_box = False
+        has_flow = False
+
+        block_fixed = False
+        has_fixed = False
+        supported: set[Sizing] = set()
+
+        box_flow_fixed = (
+            _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED
+        )
+        flow_fixed = _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED
+        given_box = _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.WH_GIVEN
+
+        # This is a set of _ContainerElementSizingFlag ORed together.
+        flags: set[int] = set()
+
+        for idx, (widget, (size_kind, _size_weight, is_box)) in enumerate(self.contents):
+            w_sizing = widget.sizing()
+
+            flag = _ContainerElementSizingFlag.NONE
+
+            if size_kind == WHSettings.WEIGHT:
+                flag |= _ContainerElementSizingFlag.WH_WEIGHT
+                if Sizing.BOX in w_sizing:
+                    flag |= _ContainerElementSizingFlag.BOX
+                if Sizing.FLOW in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FLOW
+                if Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}:
+                    flag |= _ContainerElementSizingFlag.FIXED
+
+            elif size_kind == WHSettings.GIVEN:
+                flag |= _ContainerElementSizingFlag.WH_GIVEN
+                if Sizing.BOX in w_sizing:
+                    flag |= _ContainerElementSizingFlag.BOX
+                if Sizing.FLOW in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FIXED
+                    flag |= _ContainerElementSizingFlag.FLOW
+
+            else:
+                flag |= _ContainerElementSizingFlag.WH_PACK
+                if Sizing.FIXED in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FIXED
+                if Sizing.FLOW in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FLOW
+
+            if not flag & box_flow_fixed:
+                warnings.warn(
+                    f"Sizing combination of widget {widget} (position={idx}) not supported: "
+                    f"{size_kind.name} box={is_box}",
+                    ColumnsWarning,
+                    stacklevel=3,
+                )
+                return frozenset((Sizing.BOX, Sizing.FLOW))
+
+            flags.add(flag)
+
+            if flag & _ContainerElementSizingFlag.BOX and not (is_box or flag & flow_fixed):
+                strict_box = True
+
+            if flag & _ContainerElementSizingFlag.FLOW:
+                has_flow = True
+            if flag & _ContainerElementSizingFlag.FIXED:
+                has_fixed = True
+            elif flag & given_box != given_box:
+                block_fixed = True
+
+        if all(flag & _ContainerElementSizingFlag.BOX for flag in flags):
+            # Only if ALL widgets can be rendered as BOX, widget can be rendered as BOX.
+            # Hacky "BOX" render for FLOW-only is still present,
+            # due to incorrected implementation can be used by downstream
+            supported.add(Sizing.BOX)
+
+        if not strict_box:
+            if has_flow:
+                supported.add(Sizing.FLOW)
+
+            if has_fixed and not block_fixed:
+                supported.add(Sizing.FLOW)
+                supported.add(Sizing.FIXED)
+
+        if not supported:
+            warnings.warn(
+                f"Columns widget contents flags not allow to determine supported render kind:\n"
+                f"{', '.join(sorted(_ContainerElementSizingFlag.log_string(flag) for flag in flags))}\n"
+                f"Using fallback hardcoded BOX|FLOW sizing kind.",
+                ColumnsWarning,
+                stacklevel=3,
+            )
+            return frozenset((Sizing.BOX, Sizing.FLOW))
+
+        return frozenset(supported)
+
+    def __init__(
+        self,
+        widget_list: Iterable[
+            Widget
+            | tuple[Literal["pack", WHSettings.PACK] | int, Widget]
+            | tuple[Literal["given", WHSettings.GIVEN], int, Widget]
+            | tuple[Literal["weight", WHSettings.WEIGHT], int | float, Widget]
+        ],
+        dividechars: int = 0,
+        focus_column: int | Widget | None = None,
+        min_width: int = 1,
+        box_columns: Iterable[int] | None = None,
+    ):
+        """
+        :param widget_list: iterable of flow or box widgets
+        :param dividechars: number of blank characters between columns
+        :param focus_column: index into widget_list of column in focus or focused widget instance,
+            if ``None`` the first selectable widget will be chosen.
+        :param min_width: minimum width for each column which is not
+            calling widget.pack() in *widget_list*.
+        :param box_columns: a list of column indexes containing box widgets
+            whose height is set to the maximum of the rows
+            required by columns not listed in *box_columns*.
+
+        *widget_list* may also contain tuples such as:
+
+        (*given_width*, *widget*)
+            make this column *given_width* screen columns wide, where *given_width* is an int
+        (``'pack'``, *widget*)
+            call :meth:`pack() ` to calculate the width of this column
+        (``'weight'``, *weight*, *widget*)
+            give this column a relative *weight* (number) to calculate its width from th screen columns remaining
+
+        Widgets not in a tuple are the same as (``'weight'``, ``1``, *widget*)
+
+        If the Columns widget is treated as a box widget then all children
+        are treated as box widgets, and *box_columns* is ignored.
+
+        If the Columns widget is treated as a flow widget then the rows
+        are calculated as the largest rows() returned from all columns
+        except the ones listed in *box_columns*.  The box widgets in
+        *box_columns* will be displayed with this calculated number of rows,
+        filling the full height.
+        """
+        self._selectable = False
+        self._cache_column_widths: list[int] = []
+        super().__init__()
+        self._contents: MonitoredFocusList[
+            tuple[
+                Widget,
+                tuple[Literal[WHSettings.PACK], None, bool]
+                | tuple[Literal[WHSettings.GIVEN], int, bool]
+                | tuple[Literal[WHSettings.WEIGHT], int | float, bool],
+            ],
+        ] = MonitoredFocusList()
+        self._contents.set_modified_callback(self._contents_modified)
+        self._contents.set_focus_changed_callback(lambda f: self._invalidate())
+        self._contents.set_validate_contents_modified(self._validate_contents_modified)
+
+        box_columns = set(box_columns or ())
+
+        for i, original in enumerate(widget_list):
+            w = original
+            if not isinstance(w, tuple):
+                self.contents.append((w, (WHSettings.WEIGHT, 1, i in box_columns)))
+            elif w[0] in {Sizing.FLOW, WHSettings.PACK}:  # 'pack' used to be called 'flow'
+                _ignored, w = w
+                self.contents.append((w, (WHSettings.PACK, None, i in box_columns)))
+            elif len(w) == 2 or w[0] in {Sizing.FIXED, WHSettings.GIVEN}:  # backwards compatibility: FIXED -> GIVEN
+                width, w = w[-2:]
+                self.contents.append((w, (WHSettings.GIVEN, width, i in box_columns)))
+            elif w[0] == WHSettings.WEIGHT:
+                _ignored, width, w = w
+                self.contents.append((w, (WHSettings.WEIGHT, width, i in box_columns)))
+            else:
+                raise ColumnsError(f"initial widget list item invalid: {original!r}")
+            if focus_column == w or (focus_column is None and w.selectable()):
+                focus_column = i
+
+            if not isinstance(w, Widget):
+                warnings.warn(f"{w!r} is not a Widget", ColumnsWarning, stacklevel=3)
+
+        self.dividechars = dividechars
+
+        if self.contents and focus_column is not None:
+            self.focus_position = focus_column
+        self.pref_col = None
+        self.min_width = min_width
+        self._cache_maxcol = None
+
+    def _repr_words(self) -> list[str]:
+        if len(self.contents) > 1:
+            contents_string = f"({len(self.contents)} items)"
+        elif self.contents:
+            contents_string = "(1 item)"
+        else:
+            contents_string = "()"
+        return [*super()._repr_words(), contents_string]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "dividechars": self.dividechars,
+            "focus_column": self.focus_position if len(self._contents) > 1 else None,
+            "min_width": self.min_width,
+        }
+        return remove_defaults(attrs, Columns.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        widget_list: list[
+            Widget
+            | tuple[Literal[WHSettings.PACK] | int, Widget]
+            | tuple[Literal[WHSettings.WEIGHT], int | float, Widget]
+        ] = []
+        box_columns: list[int] = []
+        for idx, (w_instance, (sizing, amount, is_box)) in enumerate(self._contents):
+            if sizing == WHSettings.GIVEN:
+                widget_list.append((amount, w_instance))
+            elif sizing == WHSettings.PACK:
+                widget_list.append((WHSettings.PACK, w_instance))
+            elif amount == 1:
+                widget_list.append(w_instance)
+            else:
+                widget_list.append((WHSettings.WEIGHT, amount, w_instance))
+
+            if is_box:
+                box_columns.append(idx)
+
+        yield "widget_list", widget_list
+        yield "dividechars", self.dividechars
+        yield "focus_column", self.focus_position if self._contents else None
+        yield "min_width", self.min_width
+        yield "box_columns", box_columns
+
+    def __len__(self) -> int:
+        return len(self._contents)
+
+    def _contents_modified(self) -> None:
+        """
+        Recalculate whether this widget should be selectable whenever the
+        contents has been changed.
+        """
+        self._selectable = any(w.selectable() for w, o in self.contents)
+        self._invalidate()
+
+    def _validate_contents_modified(self, slc, new_items) -> None:
+        invalid_items: list[tuple[Widget, tuple[typing.Any, typing.Any, typing.Any]]] = []
+        try:
+            for item in new_items:
+                _w, (t, n, b) = item
+                if any(
+                    (
+                        t not in {WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT},
+                        (n is not None and (not isinstance(n, (int, float)) or n < 0)),
+                        not isinstance(b, bool),
+                    )
+                ):
+                    invalid_items.append(item)
+        except (TypeError, ValueError) as exc:
+            raise ColumnsError(f"added content invalid {exc}").with_traceback(exc.__traceback__) from exc
+
+        if invalid_items:
+            raise ColumnsError(f"added content invalid: {invalid_items!r}")
+
+    @property
+    def widget_list(self) -> MonitoredList:
+        """
+        A list of the widgets in this Columns
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`contents`.
+        """
+        warnings.warn(
+            "only for backwards compatibility. You should use the new standard container `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(w for w, t in self.contents)
+
+        def user_modified():
+            self.widget_list = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @widget_list.setter
+    def widget_list(self, widgets):
+        warnings.warn(
+            "only for backwards compatibility. You should use the new standard container `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        focus_position = self.focus_position
+        self.contents = [
+            # need to grow contents list if widgets is longer
+            (new, options)
+            for (new, (w, options)) in zip(
+                widgets,
+                chain(self.contents, repeat((None, (WHSettings.WEIGHT, 1, False)))),
+            )
+        ]
+        if focus_position < len(widgets):
+            self.focus_position = focus_position
+
+    @property
+    def column_types(self) -> MonitoredList:
+        """
+        A list of the old partial options values for widgets in this Pile,
+        for backwards compatibility only.  You should use the new standard
+        container property .contents to modify Pile contents.
+        """
+        warnings.warn(
+            "for backwards compatibility only."
+            "You should use the new standard container property .contents to modify Pile contents."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(
+            # return the old column type names
+            ({WHSettings.GIVEN: Sizing.FIXED, WHSettings.PACK: Sizing.FLOW}.get(t, t), n)
+            for w, (t, n, b) in self.contents
+        )
+
+        def user_modified():
+            self.column_types = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @column_types.setter
+    def column_types(self, column_types):
+        warnings.warn(
+            "for backwards compatibility only."
+            "You should use the new standard container property .contents to modify Pile contents."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        focus_position = self.focus_position
+        self.contents = [
+            (w, ({Sizing.FIXED: WHSettings.GIVEN, Sizing.FLOW: WHSettings.PACK}.get(new_t, new_t), new_n, b))
+            for ((new_t, new_n), (w, (t, n, b))) in zip(column_types, self.contents)
+        ]
+        if focus_position < len(column_types):
+            self.focus_position = focus_position
+
+    @property
+    def box_columns(self) -> MonitoredList:
+        """
+        A list of the indexes of the columns that are to be treated as
+        box widgets when the Columns is treated as a flow widget.
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`contents`.
+        """
+        warnings.warn(
+            "only for backwards compatibility.You should use the new standard container property `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(i for i, (w, (t, n, b)) in enumerate(self.contents) if b)
+
+        def user_modified():
+            self.box_columns = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @box_columns.setter
+    def box_columns(self, box_columns):
+        warnings.warn(
+            "only for backwards compatibility.You should use the new standard container property `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        box_columns = set(box_columns)
+        self.contents = [(w, (t, n, i in box_columns)) for (i, (w, (t, n, b))) in enumerate(self.contents)]
+
+    @property
+    def has_flow_type(self) -> bool:
+        """
+        .. deprecated:: 1.0 Read values from :attr:`contents` instead.
+        """
+        warnings.warn(
+            ".has_flow_type is deprecated, read values from .contents instead. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return WHSettings.PACK in self.column_types
+
+    @has_flow_type.setter
+    def has_flow_type(self, value):
+        warnings.warn(
+            ".has_flow_type is deprecated, read values from .contents instead. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    @property
+    def contents(
+        self,
+    ) -> MonitoredFocusList[
+        tuple[
+            Widget,
+            tuple[Literal[WHSettings.PACK], None, bool]
+            | tuple[Literal[WHSettings.GIVEN], int, bool]
+            | tuple[Literal[WHSettings.WEIGHT], int | float, bool],
+        ],
+    ]:
+        """
+        The contents of this Columns as a list of `(widget, options)` tuples.
+        This list may be modified like a normal list and the Columns
+        widget will update automatically.
+
+        .. seealso:: Create new options tuples with the :meth:`options` method
+        """
+        return self._contents
+
+    @contents.setter
+    def contents(
+        self,
+        c: Sequence[
+            Widget,
+            tuple[Literal[WHSettings.PACK], None, bool]
+            | tuple[Literal[WHSettings.GIVEN], int, bool]
+            | tuple[Literal[WHSettings.WEIGHT], int | float, bool],
+        ],
+    ) -> None:
+        self._contents[:] = c
+
+    @staticmethod
+    def options(
+        width_type: Literal[
+            "pack", "given", "weight", WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT
+        ] = WHSettings.WEIGHT,
+        width_amount: int | float | None = 1,  # noqa: PYI041  # provide explicit for IDEs
+        box_widget: bool = False,
+    ) -> (
+        tuple[Literal[WHSettings.PACK], None, bool]
+        | tuple[Literal[WHSettings.GIVEN], int, bool]
+        | tuple[Literal[WHSettings.WEIGHT], int | float, bool]
+    ):
+        """
+        Return a new options tuple for use in a Pile's .contents list.
+
+        This sets an entry's width type: one of the following:
+
+        ``'pack'``
+            Call the widget's :meth:`Widget.pack` method to determine how wide
+            this column should be. *width_amount* is ignored.
+        ``'given'``
+            Make column exactly width_amount screen-columns wide.
+        ``'weight'``
+            Allocate the remaining space to this column by using
+            *width_amount* as a weight value.
+
+        :param width_type: ``'pack'``, ``'given'`` or ``'weight'``
+        :param width_amount: ``None`` for ``'pack'``, a number of screen columns
+            for ``'given'`` or a weight value (number) for ``'weight'``
+        :param box_widget: set to `True` if this widget is to be treated as a box
+            widget when the Columns widget itself is treated as a flow widget.
+        :type box_widget: bool
+        """
+        if width_type == WHSettings.PACK:
+            return (WHSettings.PACK, None, box_widget)
+        if width_type in {WHSettings.GIVEN, WHSettings.WEIGHT} and width_amount is not None:
+            return (WHSettings(width_type), width_amount, box_widget)
+        raise ColumnsError(f"invalid combination: width_type={width_type!r}, width_amount={width_amount!r}")
+
+    def _invalidate(self) -> None:
+        self._cache_maxcol = None
+        super()._invalidate()
+
+    def set_focus_column(self, num: int) -> None:
+        """
+        Set the column in focus by its index in :attr:`widget_list`.
+
+        :param num: index of focus-to-be entry
+        :type num: int
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus_position` to set the focus.
+        """
+        warnings.warn(
+            "only for backwards compatibility.You may also use the new standard container property `focus_position`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.focus_position = num
+
+    def get_focus_column(self) -> int:
+        """
+        Return the focus column index.
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus_position` to get the focus.
+        """
+        warnings.warn(
+            "only for backwards compatibility.You may also use the new standard container property `focus_position`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.focus_position
+
+    def set_focus(self, item: Widget | int) -> None:
+        """
+        Set the item in focus
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus_position` to get the focus.
+
+        :param item: widget or integer index"""
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus_position` to get the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if isinstance(item, int):
+            self.focus_position = item
+            return
+        for i, (w, _options) in enumerate(self.contents):
+            if item == w:
+                self.focus_position = i
+                return
+        raise ValueError(f"Widget not found in Columns contents: {item!r}")
+
+    @property
+    def focus(self) -> Widget | None:
+        """
+        the child widget in focus or None when Columns is empty
+
+        Return the widget in focus, for backwards compatibility.  You may
+        also use the new standard container property .focus to get the
+        child widget in focus.
+        """
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    def get_focus(self):
+        """
+        Return the widget in focus, for backwards compatibility.
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus` to get the focus.
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus` to get the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    @property
+    def focus_position(self) -> int | None:
+        """
+        index of child widget in focus.
+        Raises :exc:`IndexError` if read when Columns is empty, or when set to an invalid index.
+        """
+        if not self.contents:
+            raise IndexError("No focus_position, Columns is empty")
+        return self.contents.focus
+
+    @focus_position.setter
+    def focus_position(self, position: int) -> None:
+        """
+        Set the widget in focus.
+
+        position -- index of child widget to be made focus
+        """
+        try:
+            if position < 0 or position >= len(self.contents):
+                raise IndexError(f"No Columns child widget at position {position}")
+        except TypeError as exc:
+            raise IndexError(f"No Columns child widget at position {position}").with_traceback(
+                exc.__traceback__
+            ) from exc
+        self.contents.focus = position
+
+    @property
+    def focus_col(self):
+        """
+        A property for reading and setting the index of the column in
+        focus.
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus_position` to get the focus.
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus_position` to get the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.focus_position
+
+    @focus_col.setter
+    def focus_col(self, new_position) -> None:
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus_position` to get the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.focus_position = new_position
+
+    def column_widths(self, size: tuple[int] | tuple[int, int], focus: bool = False) -> list[int]:
+        """
+        Return a list of column widths.
+
+        0 values in the list means hide the corresponding column completely
+        """
+        maxcol = size[0]
+        # FIXME: get rid of this check and recalculate only when a 'pack' widget has been modified.
+        if maxcol == self._cache_maxcol and not any(t == WHSettings.PACK for w, (t, n, b) in self.contents):
+            return self._cache_column_widths
+
+        widths = []
+
+        weighted = []
+        shared = maxcol + self.dividechars
+
+        for i, (w, (t, width, b)) in enumerate(self.contents):
+            if t == WHSettings.GIVEN:
+                static_w = width
+            elif t == WHSettings.PACK:
+                if isinstance(w, Widget):
+                    w_sizing = w.sizing()
+                else:
+                    warnings.warn(f"{w!r} is not a Widget", ColumnsWarning, stacklevel=3)
+                    w_sizing = frozenset((urwid.BOX, urwid.FLOW))
+
+                if w_sizing & frozenset((Sizing.FIXED, Sizing.FLOW)):
+                    candidate_size = 0
+
+                    if Sizing.FIXED in w_sizing:
+                        candidate_size = w.pack((), focus and i == self.focus_position)[0]
+
+                    if Sizing.FLOW in w_sizing and (not candidate_size or candidate_size > maxcol):
+                        # FIXME: should be able to pack with a different maxcol value
+                        candidate_size = w.pack((maxcol,), focus and i == self.focus_position)[0]
+
+                    static_w = candidate_size
+
+                else:
+                    warnings.warn(
+                        f"Unusual widget {w} sizing for {t} (box={b}). "
+                        f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for width calculation",
+                        ColumnsWarning,
+                        stacklevel=3,
+                    )
+                    static_w = w.pack((maxcol,), focus and i == self.focus_position)[0]
+
+            else:
+                static_w = self.min_width
+
+            if shared < static_w + self.dividechars and i > self.focus_position:
+                break
+
+            widths.append(static_w)
+            shared -= static_w + self.dividechars
+            if t not in {WHSettings.GIVEN, WHSettings.PACK}:
+                weighted.append((width, i))
+
+        # drop columns on the left until we fit
+        for i, width_ in enumerate(widths):
+            if shared >= 0:
+                break
+            shared += width_ + self.dividechars
+            widths[i] = 0
+            if weighted and weighted[0][1] == i:
+                del weighted[0]
+
+        if shared:
+            # divide up the remaining space between weighted cols
+            wtotal = sum(weight for weight, i in weighted)
+            grow = shared + len(weighted) * self.min_width
+            for weight, i in sorted(weighted):
+                width = max(int(grow * weight / wtotal + 0.5), self.min_width)
+
+                widths[i] = width
+                grow -= width
+                wtotal -= weight
+
+        self._cache_maxcol = maxcol
+        self._cache_column_widths = widths
+        return widths
+
+    def _get_fixed_column_sizes(
+        self,
+        focus: bool = False,
+    ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int] | tuple[()]]]:
+        """Get column widths, heights and render size parameters"""
+        widths: dict[int, int] = {}
+        heights: dict[int, int] = {}
+        w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {}
+        box: list[int] = []
+        weighted: dict[int, list[tuple[Widget, int, bool, bool]]] = {}
+        weights: list[int] = []
+        weight_max_sizes: dict[int, int] = {}
+
+        for i, (widget, (size_kind, size_weight, is_box)) in enumerate(self.contents):
+            w_sizing = widget.sizing()
+            focused = focus and i == self.focus_position
+
+            if size_kind == WHSettings.GIVEN:
+                widths[i] = size_weight
+                if is_box:
+                    box.append(i)
+                elif Sizing.FLOW in w_sizing:
+                    heights[i] = widget.rows((size_weight,), focused)
+                    w_h_args[i] = (size_weight,)
+                else:
+                    raise ColumnsError(f"Unsupported combination of {size_kind} box={is_box!r} for {widget}")
+
+            elif size_kind == WHSettings.PACK and Sizing.FIXED in w_sizing and not is_box:
+                width, height = widget.pack((), focused)
+                widths[i] = width
+                heights[i] = height
+                w_h_args[i] = ()
+
+            elif size_weight <= 0:
+                widths[i] = 0
+                heights[i] = 1
+                if is_box:
+                    box.append(i)
+                else:
+                    w_h_args[i] = (0,)
+
+            elif Sizing.FLOW in w_sizing or is_box:
+                if Sizing.FIXED in w_sizing:
+                    width, height = widget.pack((), focused)
+                else:
+                    width = self.min_width
+
+                weighted.setdefault(size_weight, []).append((widget, i, is_box, focused))
+                weights.append(size_weight)
+                weight_max_sizes.setdefault(size_weight, width)
+                weight_max_sizes[size_weight] = max(weight_max_sizes[size_weight], width)
+            else:
+                raise ColumnsError(f"Unsupported combination of {size_kind} box={is_box!r} for {widget}")
+
+        if weight_max_sizes:
+            max_weighted_coefficient = max(width / weight for weight, width in weight_max_sizes.items())
+
+            for weight in weight_max_sizes:
+                width = max(int(max_weighted_coefficient * weight + 0.5), self.min_width)
+                for widget, i, is_box, focused in weighted[weight]:
+                    widths[i] = width
+
+                    if not is_box:
+                        heights[i] = widget.rows((width,), focused)
+                        w_h_args[i] = (width,)
+                    else:
+                        box.append(i)
+
+        if not heights:
+            raise ColumnsError(f"No height information for pack {self!r} as FIXED")
+
+        max_height = max(heights.values())
+        for idx in box:
+            heights[idx] = max_height
+            w_h_args[idx] = (widths[idx], max_height)
+
+        return (
+            tuple(widths[idx] for idx in range(len(widths))),
+            tuple(heights[idx] for idx in range(len(heights))),
+            tuple(w_h_args[idx] for idx in range(len(w_h_args))),
+        )
+
+    def get_column_sizes(
+        self,
+        size: tuple[int, int] | tuple[int] | tuple[()],
+        focus: bool = False,
+    ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int, int] | tuple[int] | tuple[()]]]:
+        """Get column widths, heights and render size parameters"""
+        if not size:
+            return self._get_fixed_column_sizes(focus=focus)
+
+        widths = tuple(self.column_widths(size=size, focus=focus))
+        heights: dict[int, int] = {}
+        w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {}
+        box: list[int] = []
+        box_need_height: list[int] = []
+
+        for i, (width, (widget, (size_kind, _size_weight, is_box))) in enumerate(zip(widths, self.contents)):
+            if isinstance(widget, Widget):
+                w_sizing = widget.sizing()
+            else:
+                warnings.warn(f"{widget!r} is not Widget.", ColumnsWarning, stacklevel=3)
+                # This branch should be fully deleted later.
+                w_sizing = frozenset((Sizing.FLOW, Sizing.BOX))
+
+            if len(size) == 2 and Sizing.BOX in w_sizing:
+                heights[i] = size[1]
+                w_h_args[i] = (width, size[1])
+
+            elif is_box:
+                box.append(i)
+
+            elif Sizing.FLOW in w_sizing:
+                if width > 0:
+                    heights[i] = widget.rows((width,), focus and i == self.focus_position)
+                else:
+                    heights[i] = 0
+                w_h_args[i] = (width,)
+
+            elif size_kind == WHSettings.PACK:
+                if width > 0:
+                    heights[i] = widget.pack((), focus and i == self.focus_position)[1]
+                else:
+                    heights[i] = 0
+                w_h_args[i] = ()
+
+            else:
+                box_need_height.append(i)
+
+        if len(size) == 1:
+            if heights:
+                max_height = max(heights.values())
+                if box_need_height:
+                    warnings.warn(
+                        f"Widgets in columns {box_need_height} "
+                        f"({[self.contents[i][0] for i in box_need_height]}) "
+                        f'are BOX widgets not marked "box_columns" while FLOW render is requested (size={size!r})',
+                        ColumnsWarning,
+                        stacklevel=3,
+                    )
+            else:
+                max_height = 1
+        else:
+            max_height = size[1]
+
+        for idx in (*box, *box_need_height):
+            heights[idx] = max_height
+            w_h_args[idx] = (widths[idx], max_height)
+
+        return (
+            widths,
+            tuple(heights[idx] for idx in range(len(heights))),
+            tuple(w_h_args[idx] for idx in range(len(w_h_args))),
+        )
+
+    def pack(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int] = (),
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        """Get packed sized for widget."""
+        if size:
+            return super().pack(size, focus)
+        widths, heights, _ = self.get_column_sizes(size, focus)
+        return (sum(widths) + self.dividechars * max(len(widths) - 1, 0), max(heights))
+
+    def render(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        focus: bool = False,
+    ) -> SolidCanvas | CompositeCanvas:
+        """
+        Render columns and return canvas.
+
+        :param size: see :meth:`Widget.render` for details
+        :param focus: ``True`` if this widget is in focus
+        :type focus: bool
+        """
+        widths, _, size_args = self.get_column_sizes(size, focus)
+
+        data: list[tuple[Canvas, int, bool, int]] = []
+        for i, (width, w_size, (w, _)) in enumerate(zip(widths, size_args, self.contents)):
+            # if the widget has a width of 0, hide it
+            if width <= 0:
+                continue
+
+            if i < len(widths) - 1:
+                width += self.dividechars  # noqa: PLW2901
+            data.append(
+                (
+                    w.render(w_size, focus=focus and self.focus_position == i),
+                    i,
+                    self.focus_position == i,
+                    width,
+                )
+            )
+
+        if not data:
+            if size:
+                return SolidCanvas(" ", size[0], (*size[1:], 1)[0])
+            raise ColumnsError("No data to render")
+
+        canvas = CanvasJoin(data)
+        if size and canvas.cols() < size[0]:
+            canvas.pad_trim_left_right(0, size[0] - canvas.cols())
+        return canvas
+
+    def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None:
+        """Return the cursor coordinates from the focus widget."""
+        w, _ = self.contents[self.focus_position]
+
+        if not w.selectable():
+            return None
+        if not hasattr(w, "get_cursor_coords"):
+            return None
+
+        widths, _, size_args = self.get_column_sizes(size, focus=True)
+        if len(widths) <= self.focus_position:
+            return None
+
+        if (coords := w.get_cursor_coords(size_args[self.focus_position])) is not None:
+            x, y = coords
+            x += sum(self.dividechars + wc for wc in widths[: self.focus_position] if wc > 0)
+            return x, y
+
+        return None
+
+    def move_cursor_to_coords(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        col: int | Literal["left", "right"],
+        row: int,
+    ) -> bool:
+        """
+        Choose a selectable column to focus based on the coords.
+
+        see :meth:`Widget.move_cursor_coords` for details
+        """
+        try:
+            widths, _, size_args = self.get_column_sizes(size, focus=True)
+        except Exception as exc:
+            raise ValueError(self.contents, size, col, row) from exc
+
+        best = None
+        x = 0
+        for i, (width, (w, _options)) in enumerate(zip(widths, self.contents)):
+            end = x + width
+            if w.selectable():
+                if col != Align.RIGHT and (col == Align.LEFT or x > col) and best is None:
+                    # no other choice
+                    best = i, x, end, w
+                    break
+                if col != Align.RIGHT and x > col and col - best[2] < x - col:
+                    # choose one on left
+                    break
+                best = i, x, end, w
+                if col != Align.RIGHT and col < end:
+                    # choose this one
+                    break
+            x = end + self.dividechars
+
+        if best is None:
+            return False
+        i, x, end, w = best
+        if hasattr(w, "move_cursor_to_coords"):
+            if isinstance(col, int):
+                move_x = min(max(0, col - x), end - x - 1)
+            else:
+                move_x = col
+
+            if w.move_cursor_to_coords(size_args[i], move_x, row) is False:
+                return False
+
+        self.focus_position = i
+        self.pref_col = col
+        return True
+
+    def mouse_event(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """
+        Send event to appropriate column.
+        May change focus on button 1 press.
+        """
+        widths, _, size_args = self.get_column_sizes(size, focus=focus)
+
+        x = 0
+        for i, (width, w_size, (w, _)) in enumerate(zip(widths, size_args, self.contents)):
+            if col < x:
+                return False
+            w = self.contents[i][0]  # noqa: PLW2901
+            end = x + width
+
+            if col >= end:
+                x = end + self.dividechars
+                continue
+
+            focus = focus and self.focus_position == i
+            if is_mouse_press(event) and button == 1 and w.selectable():
+                self.focus_position = i
+
+            if not hasattr(w, "mouse_event"):
+                warnings.warn(
+                    f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget",
+                    DeprecationWarning,
+                    stacklevel=2,
+                )
+                return False
+
+            return w.mouse_event(w_size, event, button, col - x, row, focus)
+        return False
+
+    def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int:
+        """Return the pref col from the column in focus."""
+        widths, _, size_args = self.get_column_sizes(size, focus=True)
+
+        w, _ = self.contents[self.focus_position]
+        if len(widths) <= self.focus_position:
+            return 0
+        col = None
+        cwidth = widths[self.focus_position]
+
+        if hasattr(w, "get_pref_col"):
+            col = w.get_pref_col(size_args[self.focus_position])
+            if isinstance(col, int):
+                col += self.focus_position * self.dividechars
+                col += sum(widths[: self.focus_position])
+        if col is None:
+            col = self.pref_col
+
+        if col is None and w.selectable():
+            col = cwidth // 2
+            col += self.focus_position * self.dividechars
+            col += sum(widths[: self.focus_position])
+        return col
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """
+        Return the number of rows required by the columns.
+        This only makes sense if :attr:`widget_list` contains flow widgets.
+
+        see :meth:`Widget.rows` for details
+        """
+        _, heights, _ = self.get_column_sizes(size, focus)
+        if heights:
+            return max(1, *heights)
+        return 1
+
+    def keypress(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        key: str,
+    ) -> str | None:
+        """
+        Pass keypress to the focus column.
+
+        :param size: Widget size correct for the supported sizing
+        :type size: tuple[()] | tuple[int] | tuple[int, int]
+        :param key: a single keystroke value
+        :type key: str
+        """
+        if self.focus_position is None:
+            return key
+
+        widths, _, size_args = self.get_column_sizes(size, focus=True)
+        if self.focus_position >= len(widths):
+            return key
+
+        i = self.focus_position
+        w, _ = self.contents[i]
+        if self._command_map[key] not in {Command.UP, Command.DOWN, Command.PAGE_UP, Command.PAGE_DOWN}:
+            self.pref_col = None
+        if w.selectable():
+            key = w.keypress(size_args[i], key)
+
+        if self._command_map[key] not in {Command.LEFT, Command.RIGHT}:
+            return key
+
+        if self._command_map[key] == Command.LEFT:
+            candidates = list(range(i - 1, -1, -1))  # count backwards to 0
+        else:  # key == 'right'
+            candidates = list(range(i + 1, len(self.contents)))
+
+        for j in candidates:
+            if not self.contents[j][0].selectable():
+                continue
+
+            self.focus_position = j
+            return None
+        return key
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/constants.py b/python/user_packages/Python313/site-packages/urwid/widget/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..26a56f2b49e2a0f6379d84bfe29aa8d5ec1628b4
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/constants.py
@@ -0,0 +1,555 @@
+from __future__ import annotations
+
+import dataclasses
+import enum
+import typing
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+
+# define some names for these constants to avoid misspellings in the source
+# and to document the constant strings we are using
+
+
+class Sizing(str, enum.Enum):
+    """Widget sizing methods."""
+
+    FLOW = "flow"
+    BOX = "box"
+    FIXED = "fixed"
+
+
+class Align(str, enum.Enum):
+    """Text alignment modes"""
+
+    LEFT = "left"
+    RIGHT = "right"
+    CENTER = "center"
+
+
+class VAlign(str, enum.Enum):
+    """Filler alignment"""
+
+    TOP = "top"
+    MIDDLE = "middle"
+    BOTTOM = "bottom"
+
+
+class WrapMode(str, enum.Enum):
+    """Text wrapping modes"""
+
+    SPACE = "space"
+    ANY = "any"
+    CLIP = "clip"
+    ELLIPSIS = "ellipsis"
+
+
+class WHSettings(str, enum.Enum):
+    """Width and Height settings"""
+
+    PACK = "pack"
+    GIVEN = "given"
+    RELATIVE = "relative"
+    WEIGHT = "weight"
+    CLIP = "clip"  # Used as "given" for widgets with fixed width (with clipping part of it)
+    FLOW = "flow"  # Used as pack for flow widgets
+
+
+RELATIVE_100 = (WHSettings.RELATIVE, 100)
+
+
+@typing.overload
+def normalize_align(
+    align: Literal["left", "center", "right"] | Align,
+    err: type[BaseException],
+) -> tuple[Align, None]: ...
+
+
+@typing.overload
+def normalize_align(
+    align: tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+def normalize_align(
+    align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[Align, None] | tuple[Literal[WHSettings.RELATIVE], int]:
+    """
+    Split align into (align_type, align_amount).  Raise exception err
+    if align doesn't match a valid alignment.
+    """
+    if align in {Align.LEFT, Align.CENTER, Align.RIGHT}:
+        return (Align(align), None)
+
+    if isinstance(align, tuple) and len(align) == 2 and align[0] == WHSettings.RELATIVE:
+        _align_type, align_amount = align
+        return (WHSettings.RELATIVE, align_amount)
+
+    raise err(
+        f"align value {align!r} is not one of 'left', 'center', 'right', ('relative', percentage 0=left 100=right)"
+    )
+
+
+@typing.overload
+def simplify_align(
+    align_type: Literal["relative", WHSettings.RELATIVE],
+    align_amount: int,
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def simplify_align(
+    align_type: Literal["relative", WHSettings.RELATIVE],
+    align_amount: None,
+) -> typing.NoReturn: ...
+
+
+@typing.overload
+def simplify_align(
+    align_type: Literal["left", "center", "right"] | Align,
+    align_amount: int | None,
+) -> Align: ...
+
+
+def simplify_align(
+    align_type: Literal["left", "center", "right", "relative", WHSettings.RELATIVE] | Align,
+    align_amount: int | None,
+) -> Align | tuple[Literal[WHSettings.RELATIVE], int]:
+    """
+    Recombine (align_type, align_amount) into an align value.
+    Inverse of normalize_align.
+    """
+    if align_type == WHSettings.RELATIVE:
+        if not isinstance(align_amount, int):
+            raise TypeError(align_amount)
+
+        return (WHSettings.RELATIVE, align_amount)
+    return Align(align_type)
+
+
+@typing.overload
+def normalize_valign(
+    valign: Literal["top", "middle", "bottom"] | VAlign,
+    err: type[BaseException],
+) -> tuple[VAlign, None]: ...
+
+
+@typing.overload
+def normalize_valign(
+    valign: tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+def normalize_valign(
+    valign: Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[VAlign, None] | tuple[Literal[WHSettings.RELATIVE], int]:
+    """
+    Split align into (valign_type, valign_amount).  Raise exception err
+    if align doesn't match a valid alignment.
+    """
+    if valign in {VAlign.TOP, VAlign.MIDDLE, VAlign.BOTTOM}:
+        return (VAlign(valign), None)
+
+    if isinstance(valign, tuple) and len(valign) == 2 and valign[0] == WHSettings.RELATIVE:
+        _valign_type, valign_amount = valign
+        return (WHSettings.RELATIVE, valign_amount)
+
+    raise err(
+        f"valign value {valign!r} is not one of 'top', 'middle', 'bottom', ('relative', percentage 0=left 100=right)"
+    )
+
+
+@typing.overload
+def simplify_valign(
+    valign_type: Literal["top", "middle", "bottom"] | VAlign,
+    valign_amount: int | None,
+) -> VAlign: ...
+
+
+@typing.overload
+def simplify_valign(
+    valign_type: Literal["relative", WHSettings.RELATIVE],
+    valign_amount: int,
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def simplify_valign(
+    valign_type: Literal["relative", WHSettings.RELATIVE],
+    valign_amount: None,
+) -> typing.NoReturn: ...
+
+
+def simplify_valign(
+    valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign,
+    valign_amount: int | None,
+) -> VAlign | tuple[Literal[WHSettings.RELATIVE], int]:
+    """
+    Recombine (valign_type, valign_amount) into an valign value.
+    Inverse of normalize_valign.
+    """
+    if valign_type == WHSettings.RELATIVE:
+        if not isinstance(valign_amount, int):
+            raise TypeError(valign_amount)
+        return (WHSettings.RELATIVE, valign_amount)
+    return VAlign(valign_type)
+
+
+@typing.overload
+def normalize_width(
+    width: Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.CLIP, WHSettings.PACK], None]: ...
+
+
+@typing.overload
+def normalize_width(
+    width: int,
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.GIVEN], int]: ...
+
+
+@typing.overload
+def normalize_width(
+    width: tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def normalize_width(
+    width: tuple[Literal["weight", WHSettings.WEIGHT], int | float],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ...
+
+
+def normalize_width(
+    width: (
+        Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK]
+        | int
+        | tuple[Literal["relative", WHSettings.RELATIVE], int]
+        | tuple[Literal["weight", WHSettings.WEIGHT], int | float]
+    ),
+    err: type[BaseException],
+) -> (
+    tuple[Literal[WHSettings.CLIP, WHSettings.PACK], None]
+    | tuple[Literal[WHSettings.GIVEN, WHSettings.RELATIVE], int]
+    | tuple[Literal[WHSettings.WEIGHT], int | float]
+):
+    """
+    Split width into (width_type, width_amount).  Raise exception err
+    if width doesn't match a valid alignment.
+    """
+    if width in {WHSettings.CLIP, WHSettings.PACK}:
+        return (WHSettings(width), None)
+
+    if isinstance(width, int):
+        return (WHSettings.GIVEN, width)
+
+    if isinstance(width, tuple) and len(width) == 2 and width[0] in {WHSettings.RELATIVE, WHSettings.WEIGHT}:
+        width_type, width_amount = width
+        return (WHSettings(width_type), width_amount)
+
+    raise err(
+        f"width value {width!r} is not one of"
+        f"fixed number of columns, 'pack', ('relative', percentage of total width), 'clip'"
+    )
+
+
+@typing.overload
+def simplify_width(
+    width_type: Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK],
+    width_amount: int | None,
+) -> Literal[WHSettings.CLIP, WHSettings.PACK]: ...
+
+
+@typing.overload
+def simplify_width(
+    width_type: Literal["given", WHSettings.GIVEN],
+    width_amount: int,
+) -> int: ...
+
+
+@typing.overload
+def simplify_width(
+    width_type: Literal["relative", WHSettings.RELATIVE],
+    width_amount: int,
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def simplify_width(
+    width_type: Literal["weight", WHSettings.WEIGHT],
+    width_amount: int | float,  # noqa: PYI041  # provide explicit for IDEs
+) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ...
+
+
+@typing.overload
+def simplify_width(
+    width_type: Literal["given", "relative", "weight", WHSettings.GIVEN, WHSettings.RELATIVE, WHSettings.WEIGHT],
+    width_amount: None,
+) -> typing.NoReturn: ...
+
+
+def simplify_width(
+    width_type: Literal["clip", "pack", "given", "relative", "weight"] | WHSettings,
+    width_amount: int | float | None,  # noqa: PYI041  # provide explicit for IDEs
+) -> (
+    Literal[WHSettings.CLIP, WHSettings.PACK]
+    | int
+    | tuple[Literal[WHSettings.RELATIVE], int]
+    | tuple[Literal[WHSettings.WEIGHT], int | float]
+):
+    """
+    Recombine (width_type, width_amount) into an width value.
+    Inverse of normalize_width.
+    """
+    if width_type in {WHSettings.CLIP, WHSettings.PACK}:
+        return WHSettings(width_type)
+
+    if not isinstance(width_amount, int):
+        raise TypeError(width_amount)
+
+    if width_type == WHSettings.GIVEN:
+        return width_amount
+
+    return (WHSettings(width_type), width_amount)
+
+
+@typing.overload
+def normalize_height(
+    height: int,
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.GIVEN], int]: ...
+
+
+@typing.overload
+def normalize_height(
+    height: Literal["flow", "pack", Sizing.FLOW, WHSettings.PACK],
+    err: type[BaseException],
+) -> tuple[Literal[Sizing.FLOW, WHSettings.PACK], None]: ...
+
+
+@typing.overload
+def normalize_height(
+    height: tuple[Literal["relative", WHSettings.RELATIVE], int],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def normalize_height(
+    height: tuple[Literal["weight", WHSettings.WEIGHT], int | float],
+    err: type[BaseException],
+) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ...
+
+
+def normalize_height(
+    height: (
+        int
+        | Literal["flow", "pack", Sizing.FLOW, WHSettings.PACK]
+        | tuple[Literal["relative", WHSettings.RELATIVE], int]
+        | tuple[Literal["weight", WHSettings.WEIGHT], int | float]
+    ),
+    err: type[BaseException],
+) -> (
+    tuple[Literal[Sizing.FLOW, WHSettings.PACK], None]
+    | tuple[Literal[WHSettings.RELATIVE, WHSettings.GIVEN], int]
+    | tuple[Literal[WHSettings.WEIGHT], int | float]
+):
+    """
+    Split height into (height_type, height_amount).  Raise exception err
+    if height isn't valid.
+    """
+    if height == Sizing.FLOW:
+        return (Sizing.FLOW, None)
+
+    if height == WHSettings.PACK:
+        return (WHSettings.PACK, None)
+
+    if isinstance(height, tuple) and len(height) == 2 and height[0] in {WHSettings.RELATIVE, WHSettings.WEIGHT}:
+        return (WHSettings(height[0]), height[1])
+
+    if isinstance(height, int):
+        return (WHSettings.GIVEN, height)
+
+    raise err(
+        f"height value {height!r} is not one of "
+        f"fixed number of columns, 'pack', ('relative', percentage of total height)"
+    )
+
+
+@typing.overload
+def simplify_height(
+    height_type: Literal["flow", "pack", WHSettings.FLOW, WHSettings.PACK],
+    height_amount: int | None,
+) -> Literal[WHSettings.FLOW, WHSettings.PACK]: ...
+
+
+@typing.overload
+def simplify_height(
+    height_type: Literal["given", WHSettings.GIVEN],
+    height_amount: int,
+) -> int: ...
+
+
+@typing.overload
+def simplify_height(
+    height_type: Literal["relative", WHSettings.RELATIVE],
+    height_amount: int | None,
+) -> tuple[Literal[WHSettings.RELATIVE], int]: ...
+
+
+@typing.overload
+def simplify_height(
+    height_type: Literal["weight", WHSettings.WEIGHT],
+    height_amount: int | float | None,  # noqa: PYI041  # provide explicit for IDEs
+) -> tuple[Literal[WHSettings.WEIGHT], int | float]: ...
+
+
+@typing.overload
+def simplify_height(
+    height_type: Literal["relative", "given", "weight", WHSettings.RELATIVE, WHSettings.GIVEN, WHSettings.WEIGHT],
+    height_amount: None,
+) -> typing.NoReturn: ...
+
+
+def simplify_height(
+    height_type: Literal[
+        "flow",
+        "pack",
+        "relative",
+        "given",
+        "weight",
+        WHSettings.FLOW,
+        WHSettings.PACK,
+        WHSettings.RELATIVE,
+        WHSettings.GIVEN,
+        WHSettings.WEIGHT,
+    ],
+    height_amount: int | float | None,  # noqa: PYI041  # provide explicit for IDEs
+) -> (
+    int
+    | Literal[WHSettings.FLOW, WHSettings.PACK]
+    | tuple[Literal[WHSettings.RELATIVE], int]
+    | tuple[Literal[WHSettings.WEIGHT], int | float]
+):
+    """
+    Recombine (height_type, height_amount) into a height value.
+    Inverse of normalize_height.
+    """
+    if height_type in {WHSettings.FLOW, WHSettings.PACK}:
+        return WHSettings(height_type)
+
+    if not isinstance(height_amount, int):
+        raise TypeError(height_amount)
+
+    if height_type == WHSettings.GIVEN:
+        return height_amount
+
+    return (WHSettings(height_type), height_amount)
+
+
+@dataclasses.dataclass(frozen=True)
+class _BoxSymbols:
+    """Box symbols for drawing."""
+
+    HORIZONTAL: str
+    VERTICAL: str
+    TOP_LEFT: str
+    TOP_RIGHT: str
+    BOTTOM_LEFT: str
+    BOTTOM_RIGHT: str
+    # Joints for tables making
+    LEFT_T: str
+    RIGHT_T: str
+    TOP_T: str
+    BOTTOM_T: str
+    CROSS: str
+
+
+@dataclasses.dataclass(frozen=True)
+class _BoxSymbolsWithDashes(_BoxSymbols):
+    """Box symbols for drawing.
+
+    Extra dashes symbols.
+    """
+
+    HORIZONTAL_4_DASHES: str
+    HORIZONTAL_3_DASHES: str
+    HORIZONTAL_2_DASHES: str
+    VERTICAL_2_DASH: str
+    VERTICAL_3_DASH: str
+    VERTICAL_4_DASH: str
+
+
+@dataclasses.dataclass(frozen=True)
+class _LightBoxSymbols(_BoxSymbolsWithDashes):
+    """Box symbols for drawing.
+
+    The Thin version includes extra symbols.
+    Symbols are ordered as in Unicode except dashes.
+    """
+
+    TOP_LEFT_ROUNDED: str
+    TOP_RIGHT_ROUNDED: str
+    BOTTOM_LEFT_ROUNDED: str
+    BOTTOM_RIGHT_ROUNDED: str
+
+
+class _BoxSymbolsCollection(typing.NamedTuple):
+    """Standard Unicode box symbols for basic tables drawing.
+
+    .. note::
+        Transitions are not included: depends on line types, different kinds of transitions are available.
+        Please check Unicode table for transitions symbols if required.
+    """
+
+    # fmt: off
+
+    LIGHT: _LightBoxSymbols = _LightBoxSymbols(
+        "─", "│", "┌", "┐", "└", "┘", "├", "┤", "┬", "┴", "┼", "┈", "┄", "╌", "╎", "┆", "┊", "╭", "╮", "╰", "╯"
+    )
+    HEAVY: _BoxSymbolsWithDashes = _BoxSymbolsWithDashes(
+        "━", "┃", "┏", "┓", "┗", "┛", "┣", "┫", "┳", "┻", "╋", "┉", "┅", "╍", "╏", "┇", "┋"
+    )
+    DOUBLE: _BoxSymbols = _BoxSymbols(
+        "═", "║", "╔", "╗", "╚", "╝", "╠", "╣", "╦", "╩", "╬"
+    )
+
+
+BOX_SYMBOLS = _BoxSymbolsCollection()
+
+
+class BAR_SYMBOLS(str, enum.Enum):
+    """Standard Unicode bar symbols excluding empty space.
+
+    Start from space (0), then 1/8 till full block (1/1).
+    Typically used only 8 from this symbol collection depends on use-case:
+    * empty - 7/8 and styles for BG different on both sides (like standard `ProgressBar` and `BarGraph`)
+    * 1/8 - full block and single style for BG on the right side
+    """
+
+    # fmt: off
+
+    HORISONTAL = " ▏▎▍▌▋▊▉█"
+    VERTICAL =   " ▁▂▃▄▅▆▇█"
+
+
+class _SHADE_SYMBOLS(typing.NamedTuple):
+    """Standard shade symbols excluding empty space."""
+
+    # fmt: off
+
+    FULL_BLOCK: str =   "█"
+    DARK_SHADE: str =   "▓"
+    MEDIUM_SHADE: str = "▒"
+    LITE_SHADE: str =   "░"
+
+
+SHADE_SYMBOLS = _SHADE_SYMBOLS()
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/container.py b/python/user_packages/Python313/site-packages/urwid/widget/container.py
new file mode 100644
index 0000000000000000000000000000000000000000..82f1e24ee8d83a883b0e645195f965f5f81b3c56
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/container.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import abc
+import enum
+import typing
+
+from .constants import Sizing, WHSettings
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterable, Iterator
+
+    from .widget import Widget
+
+
+# Ideally, we would like to use an IntFlag coupled with enum.auto().
+# However, doing many bitwise operations (which happens when nesting too many
+# widgets ...) on IntFlag is orders of magnitude slower than doing the same
+# operations on IntEnum.
+class _ContainerElementSizingFlag(enum.IntEnum):
+    # fmt: off
+    NONE      = 0b000000
+    BOX       = 0b000001
+    FLOW      = 0b000010
+    FIXED     = 0b000100
+    WH_WEIGHT = 0b001000
+    WH_PACK   = 0b010000
+    WH_GIVEN  = 0b100000
+    # fmt: on
+
+    @staticmethod
+    def reverse_flag(bitfield: int) -> tuple[frozenset[Sizing], WHSettings | None]:
+        """Get flag in public API format."""
+        sizing: set[Sizing] = set()
+
+        if bitfield & _ContainerElementSizingFlag.BOX:
+            sizing.add(Sizing.BOX)
+        if bitfield & _ContainerElementSizingFlag.FLOW:
+            sizing.add(Sizing.FLOW)
+        if bitfield & _ContainerElementSizingFlag.FIXED:
+            sizing.add(Sizing.FIXED)
+
+        if bitfield & _ContainerElementSizingFlag.WH_WEIGHT:
+            return frozenset(sizing), WHSettings.WEIGHT
+        if bitfield & _ContainerElementSizingFlag.WH_PACK:
+            return frozenset(sizing), WHSettings.PACK
+        if bitfield & _ContainerElementSizingFlag.WH_GIVEN:
+            return frozenset(sizing), WHSettings.GIVEN
+        return frozenset(sizing), None
+
+    @staticmethod
+    def log_string(bitfield: int) -> str:
+        """Get desctiprion in public API format."""
+        sizing, render = _ContainerElementSizingFlag.reverse_flag(bitfield)
+        render_string = f" {render.upper()}" if render else ""
+        return "|".join(sorted(mode.upper() for mode in sizing)) + render_string
+
+
+class WidgetContainerMixin:
+    """
+    Mixin class for widget containers implementing common container methods
+    """
+
+    def __getitem__(self, position) -> Widget:
+        """
+        Container short-cut for self.contents[position][0].base_widget
+        which means "give me the child widget at position without any
+        widget decorations".
+
+        This allows for concise traversal of nested container widgets
+        such as:
+
+            my_widget[position0][position1][position2] ...
+        """
+        return self.contents[position][0].base_widget
+
+    def get_focus_path(self) -> list[int | str]:
+        """
+        Return the .focus_position values starting from this container
+        and proceeding along each child widget until reaching a leaf
+        (non-container) widget.
+        """
+        out = []
+        w = self
+        while True:
+            try:
+                p = w.focus_position
+            except IndexError:
+                return out
+            out.append(p)
+            w = w.focus.base_widget
+
+    def set_focus_path(self, positions: Iterable[int | str]) -> None:
+        """
+        Set the .focus_position property starting from this container
+        widget and proceeding along newly focused child widgets.  Any
+        failed assignment due do incompatible position types or invalid
+        positions will raise an IndexError.
+
+        This method may be used to restore a particular widget to the
+        focus by passing in the value returned from an earlier call to
+        get_focus_path().
+
+        positions -- sequence of positions
+        """
+        w: Widget = self
+        for p in positions:
+            if p != w.focus_position:
+                w.focus_position = p  # modifies w.focus
+            w = w.focus.base_widget  # type: ignore[assignment]
+
+    def get_focus_widgets(self) -> list[Widget]:
+        """
+        Return the .focus values starting from this container
+        and proceeding along each child widget until reaching a leaf
+        (non-container) widget.
+
+        Note that the list does not contain the topmost container widget
+        (i.e., on which this method is called), but does include the
+        lowest leaf widget.
+        """
+        out = []
+        w = self
+        while (w := w.base_widget.focus) is not None:
+            out.append(w)
+
+        return out
+
+    @property
+    @abc.abstractmethod
+    def focus(self) -> Widget:
+        """
+        Read-only property returning the child widget in focus for
+        container widgets.  This default implementation
+        always returns ``None``, indicating that this widget has no children.
+        """
+
+
+class WidgetContainerListContentsMixin:
+    """
+    Mixin class for widget containers whose positions are indexes into
+    a list available as self.contents.
+    """
+
+    def __iter__(self) -> Iterator[int]:
+        """
+        Return an iterable of positions for this container from first
+        to last.
+        """
+        return iter(range(len(self.contents)))
+
+    def __reversed__(self) -> Iterator[int]:
+        """
+        Return an iterable of positions for this container from last
+        to first.
+        """
+        return iter(range(len(self.contents) - 1, -1, -1))
+
+    def __len__(self) -> int:
+        return len(self.contents)
+
+    @property
+    @abc.abstractmethod
+    def contents(self) -> list[tuple[Widget, typing.Any]]:
+        """The contents of container as a list of (widget, options)"""
+
+    @contents.setter
+    def contents(self, new_contents: list[tuple[Widget, typing.Any]]) -> None:
+        """The contents of container as a list of (widget, options)"""
+
+    @property
+    @abc.abstractmethod
+    def focus_position(self) -> int | None:
+        """
+        index of child widget in focus.
+        """
+
+    @focus_position.setter
+    def focus_position(self, position: int) -> None:
+        """
+        index of child widget in focus.
+        """
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/divider.py b/python/user_packages/Python313/site-packages/urwid/widget/divider.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a621f5b5ed28173882a7ae3ec3145fc2e787402
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/divider.py
@@ -0,0 +1,114 @@
+from __future__ import annotations
+
+import enum
+import typing
+
+from urwid.canvas import CompositeCanvas, SolidCanvas
+
+from .constants import BOX_SYMBOLS, SHADE_SYMBOLS, Sizing
+from .widget import Widget
+
+
+class DividerSymbols(str, enum.Enum):
+    """Common symbols for divider widgets."""
+
+    # Lines
+    LIGHT_HL = BOX_SYMBOLS.LIGHT.HORIZONTAL
+    LIGHT_4_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_4_DASHES
+    LIGHT_3_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_3_DASHES
+    LIGHT_2_DASHES = BOX_SYMBOLS.LIGHT.HORIZONTAL_2_DASHES
+    HEAVY_HL = BOX_SYMBOLS.HEAVY.HORIZONTAL
+    HEAVY_4_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_4_DASHES
+    HEAVY_3_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_3_DASHES
+    HEAVY_2_DASHES = BOX_SYMBOLS.HEAVY.HORIZONTAL_2_DASHES
+    DOUBLE_HL = BOX_SYMBOLS.DOUBLE.HORIZONTAL
+
+    # Full block
+    FULL_BLOCK = SHADE_SYMBOLS.FULL_BLOCK
+    DARK_SHADE = SHADE_SYMBOLS.DARK_SHADE
+    MEDIUM_SHADE = SHADE_SYMBOLS.MEDIUM_SHADE
+    LITE_SHADE = SHADE_SYMBOLS.LITE_SHADE
+
+
+class Divider(Widget):
+    """
+    Horizontal divider widget
+    """
+
+    Symbols = DividerSymbols
+
+    _sizing = frozenset([Sizing.FLOW])
+
+    ignore_focus = True
+
+    def __init__(
+        self,
+        div_char: str | bytes = " ",
+        top: int = 0,
+        bottom: int = 0,
+    ) -> None:
+        """
+        :param div_char: character to repeat across line
+        :type div_char: bytes or unicode
+
+        :param top: number of blank lines above
+        :type top: int
+
+        :param bottom: number of blank lines below
+        :type bottom: int
+
+        >>> Divider()
+        
+        >>> Divider("-")
+        
+        >>> Divider("x", 1, 2)
+        
+        """
+        super().__init__()
+        self.div_char = div_char
+        self.top = top
+        self.bottom = bottom
+
+    def _repr_words(self) -> list[str]:
+        return super()._repr_words() + [repr(self.div_char)] * (self.div_char != " ")
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = dict(super()._repr_attrs())
+        if self.top:
+            attrs["top"] = self.top
+        if self.bottom:
+            attrs["bottom"] = self.bottom
+        return attrs
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """
+        Return the number of lines that will be rendered.
+
+        >>> Divider().rows((10,))
+        1
+        >>> Divider("x", 1, 2).rows((10,))
+        4
+        """
+        (_maxcol,) = size
+        return self.top + 1 + self.bottom
+
+    def render(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        """
+        Render the divider as a canvas and return it.
+
+        >>> Divider().render((10,)).text  # ... = b in Python 3
+        [...'          ']
+        >>> Divider("-", top=1).render((10,)).text
+        [...'          ', ...'----------']
+        >>> Divider("x", bottom=2).render((5,)).text
+        [...'xxxxx', ...'     ', ...'     ']
+        """
+        (maxcol,) = size
+        canv = CompositeCanvas(SolidCanvas(self.div_char, maxcol, 1))
+        if self.top or self.bottom:
+            canv.pad_trim_top_bottom(self.top, self.bottom)
+        return canv
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/edit.py b/python/user_packages/Python313/site-packages/urwid/widget/edit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ba166533aa518a3fdef4dc9a3321e3c0e153da1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/edit.py
@@ -0,0 +1,724 @@
+from __future__ import annotations
+
+import string
+import typing
+
+from urwid import text_layout
+from urwid.canvas import CompositeCanvas
+from urwid.command_map import Command
+from urwid.split_repr import remove_defaults
+from urwid.str_util import is_wide_char, move_next_char, move_prev_char
+from urwid.util import decompose_tagmarkup
+
+from .constants import Align, Sizing, WrapMode
+from .text import Text, TextError
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable
+
+    from typing_extensions import Literal
+
+    from urwid.canvas import TextCanvas
+
+
+class EditError(TextError):
+    pass
+
+
+class Edit(Text):
+    """
+    Text editing widget implements cursor movement, text insertion and
+    deletion.  A caption may prefix the editing area.  Uses text class
+    for text layout.
+
+    Users of this class may listen for ``"change"`` or ``"postchange"``
+    events.  See :func:``connect_signal``.
+
+    * ``"change"`` is sent just before the value of edit_text changes.
+      It receives the new text as an argument.  Note that ``"change"`` cannot
+      change the text in question as edit_text changes the text afterwards.
+    * ``"postchange"`` is sent after the value of edit_text changes.
+      It receives the old value of the text as an argument and thus is
+      appropriate for changing the text.  It is possible for a ``"postchange"``
+      event handler to get into a loop of changing the text and then being
+      called when the event is re-emitted.  It is up to the event
+      handler to guard against this case (for instance, by not changing the
+      text if it is signaled for text that it has already changed once).
+    """
+
+    _sizing = frozenset([Sizing.FLOW])
+    _selectable = True
+    ignore_focus = False
+    # (this variable is picked up by the MetaSignals metaclass)
+    signals: typing.ClassVar[list[str]] = ["change", "postchange"]
+
+    def valid_char(self, ch: str) -> bool:
+        """
+        Filter for text that may be entered into this widget by the user
+
+        :param ch: character to be inserted
+        :type ch: str
+
+        This implementation returns True for all printable characters.
+        """
+        return is_wide_char(ch, 0) or (len(ch) == 1 and ord(ch) >= 32)
+
+    def __init__(
+        self,
+        caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]] = "",
+        edit_text: str = "",
+        multiline: bool = False,
+        align: Literal["left", "center", "right"] | Align = Align.LEFT,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE,
+        allow_tab: bool = False,
+        edit_pos: int | None = None,
+        layout: text_layout.TextLayout = None,
+        mask: str | None = None,
+    ) -> None:
+        """
+        :param caption: markup for caption preceding edit_text, see
+                        :class:`Text` for description of text markup.
+        :type caption: text markup
+        :param edit_text: initial text for editing, type (bytes or unicode)
+                          must match the text in the caption
+        :type edit_text: bytes or unicode
+        :param multiline: True: 'enter' inserts newline  False: return it
+        :type multiline: bool
+        :param align: typically 'left', 'center' or 'right'
+        :type align: text alignment mode
+        :param wrap: typically 'space', 'any' or 'clip'
+        :type wrap: text wrapping mode
+        :param allow_tab: True: 'tab' inserts 1-8 spaces  False: return it
+        :type allow_tab: bool
+        :param edit_pos: initial position for cursor, None:end of edit_text
+        :type edit_pos: int
+        :param layout: defaults to a shared :class:`StandardTextLayout` instance
+        :type layout: text layout instance
+        :param mask: hide text entered with this character, None:disable mask
+        :type mask: bytes or unicode
+
+        >>> Edit()
+        
+        >>> Edit("Y/n? ", "yes")
+        
+        >>> Edit("Name ", "Smith", edit_pos=1)
+        
+        >>> Edit("", "3.14", align="right")
+        
+        """
+
+        super().__init__("", align, wrap, layout)
+        self.multiline = multiline
+        self.allow_tab = allow_tab
+        self._edit_pos = 0
+        self._caption, self._attrib = decompose_tagmarkup(caption)
+        self._edit_text = ""
+        self.highlight: tuple[int, int] | None = None
+        self.set_edit_text(edit_text)
+        if edit_pos is None:
+            edit_pos = len(edit_text)
+        self.set_edit_pos(edit_pos)
+        self.set_mask(mask)
+        self._shift_view_to_cursor = False
+
+    def _repr_words(self) -> list[str]:
+        return (
+            super()._repr_words()[:-1]
+            + [repr(self._edit_text)]
+            + [f"caption={self._caption!r}"] * bool(self._caption)
+            + ["multiline"] * (self.multiline is True)
+        )
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {**super()._repr_attrs(), "edit_pos": self._edit_pos}
+        return remove_defaults(attrs, Edit.__init__)
+
+    def get_text(self) -> tuple[str | bytes, list[tuple[Hashable, int]]]:
+        """
+        Returns ``(text, display attributes)``. See :meth:`Text.get_text`
+        for details.
+
+        Text returned includes the caption and edit_text, possibly masked.
+
+        >>> Edit("What? ", "oh, nothing.").get_text()
+        ('What? oh, nothing.', [])
+        >>> Edit(("bright", "user@host:~$ "), "ls").get_text()
+        ('user@host:~$ ls', [('bright', 13)])
+        >>> Edit("password:", "seekrit", mask="*").get_text()
+        ('password:*******', [])
+        """
+
+        if self._mask is None:
+            return self._caption + self._edit_text, self._attrib
+
+        return self._caption + (self._mask * len(self._edit_text)), self._attrib
+
+    def set_text(self, markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None:
+        """
+        Not supported by Edit widget.
+
+        >>> Edit().set_text("test")
+        Traceback (most recent call last):
+        EditError: set_text() not supported.  Use set_caption() or set_edit_text() instead.
+        """
+        # FIXME: this smells. reimplement Edit as a WidgetWrap subclass to
+        # clean this up
+
+        # hack to let Text.__init__() work
+        if not hasattr(self, "_text") and markup == "":  # noqa: PLC1901,RUF100
+            self._text = None
+            return
+
+        raise EditError("set_text() not supported.  Use set_caption() or set_edit_text() instead.")
+
+    def get_pref_col(self, size: tuple[int]) -> int:
+        """
+        Return the preferred column for the cursor, or the
+        current cursor x value.  May also return ``'left'`` or ``'right'``
+        to indicate the leftmost or rightmost column available.
+
+        This method is used internally and by other widgets when
+        moving the cursor up or down between widgets so that the
+        column selected is one that the user would expect.
+
+        >>> size = (10,)
+        >>> Edit().get_pref_col(size)
+        0
+        >>> e = Edit("", "word")
+        >>> e.get_pref_col(size)
+        4
+        >>> e.keypress(size, "left")
+        >>> e.get_pref_col(size)
+        3
+        >>> e.keypress(size, "end")
+        >>> e.get_pref_col(size)
+        
+        >>> e = Edit("", "2\\nwords")
+        >>> e.keypress(size, "left")
+        >>> e.keypress(size, "up")
+        >>> e.get_pref_col(size)
+        4
+        >>> e.keypress(size, "left")
+        >>> e.get_pref_col(size)
+        0
+        """
+        (maxcol,) = size
+        pref_col, then_maxcol = self.pref_col_maxcol
+        if then_maxcol != maxcol:
+            return self.get_cursor_coords((maxcol,))[0]
+
+        return pref_col
+
+    def set_caption(self, caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None:
+        """
+        Set the caption markup for this widget.
+
+        :param caption: markup for caption preceding edit_text, see
+                        :meth:`Text.__init__` for description of text markup.
+
+        >>> e = Edit("")
+        >>> e.set_caption("cap1")
+        >>> print(e.caption)
+        cap1
+        >>> e.set_caption(("bold", "cap2"))
+        >>> print(e.caption)
+        cap2
+        >>> e.attrib
+        [('bold', 4)]
+        >>> e.caption = "cap3"  # not supported because caption stores text but set_caption() takes markup
+        Traceback (most recent call last):
+        AttributeError: can't set attribute
+        """
+        self._caption, self._attrib = decompose_tagmarkup(caption)
+        self._invalidate()
+
+    @property
+    def caption(self) -> str:
+        """
+        Read-only property returning the caption for this widget.
+        """
+        return self._caption
+
+    def set_edit_pos(self, pos: int) -> None:
+        """
+        Set the cursor position with a self.edit_text offset.
+        Clips pos to [0, len(edit_text)].
+
+        :param pos: cursor position
+        :type pos: int
+
+        >>> e = Edit("", "word")
+        >>> e.edit_pos
+        4
+        >>> e.set_edit_pos(2)
+        >>> e.edit_pos
+        2
+        >>> e.edit_pos = -1  # Urwid 0.9.9 or later
+        >>> e.edit_pos
+        0
+        >>> e.edit_pos = 20
+        >>> e.edit_pos
+        4
+        """
+        pos = min(max(pos, 0), len(self._edit_text))
+        self.highlight = None
+        self.pref_col_maxcol = None, None
+        self._edit_pos = pos
+        self._invalidate()
+
+    edit_pos = property(
+        lambda self: self._edit_pos,
+        set_edit_pos,
+        doc="""
+        Property controlling the edit position for this widget.
+        """,
+    )
+
+    def set_mask(self, mask: str | None) -> None:
+        """
+        Set the character for masking text away.
+
+        :param mask: hide text entered with this character, None:disable mask
+        :type mask: bytes or unicode
+        """
+
+        self._mask = mask
+        self._invalidate()
+
+    def set_edit_text(self, text: str) -> None:
+        """
+        Set the edit text for this widget.
+
+        :param text: text for editing, type (bytes or unicode)
+                     must match the text in the caption
+        :type text: bytes or unicode
+
+        >>> e = Edit()
+        >>> e.set_edit_text("yes")
+        >>> print(e.edit_text)
+        yes
+        >>> e
+        
+        >>> e.edit_text = "no"  # Urwid 0.9.9 or later
+        >>> print(e.edit_text)
+        no
+        """
+        text = self._normalize_to_caption(text)
+        self.highlight = None
+        self._emit("change", text)
+        old_text = self._edit_text
+        self._edit_text = text
+        self.edit_pos = min(self.edit_pos, len(text))
+
+        self._emit("postchange", old_text)
+        self._invalidate()
+
+    def get_edit_text(self) -> str:
+        """
+        Return the edit text for this widget.
+
+        >>> e = Edit("What? ", "oh, nothing.")
+        >>> print(e.get_edit_text())
+        oh, nothing.
+        >>> print(e.edit_text)
+        oh, nothing.
+        """
+        return self._edit_text
+
+    edit_text = property(
+        get_edit_text,
+        set_edit_text,
+        doc="""
+        Property controlling the edit text for this widget.
+        """,
+    )
+
+    def insert_text(self, text: str) -> None:
+        """
+        Insert text at the cursor position and update cursor.
+        This method is used by the keypress() method when inserting
+        one or more characters into edit_text.
+
+        :param text: text for inserting, type (bytes or unicode)
+                     must match the text in the caption
+        :type text: bytes or unicode
+
+        >>> e = Edit("", "42")
+        >>> e.insert_text(".5")
+        >>> e
+        
+        >>> e.set_edit_pos(2)
+        >>> e.insert_text("a")
+        >>> print(e.edit_text)
+        42a.5
+        """
+        text = self._normalize_to_caption(text)
+        result_text, result_pos = self.insert_text_result(text)
+        self.set_edit_text(result_text)
+        self.set_edit_pos(result_pos)
+        self.highlight = None
+
+    def _normalize_to_caption(self, text: str | bytes) -> str | bytes:
+        """Return text converted to the same type as self.caption (bytes or unicode)"""
+        tu = isinstance(text, str)
+        cu = isinstance(self._caption, str)
+        if tu == cu:
+            return text
+        if tu:
+            return text.encode("ascii")  # follow python2's implicit conversion
+        return text.decode("ascii")
+
+    def insert_text_result(self, text: str) -> tuple[str | bytes, int]:
+        """
+        Return result of insert_text(text) without actually performing the
+        insertion.  Handy for pre-validation.
+
+        :param text: text for inserting, type (bytes or unicode)
+                     must match the text in the caption
+        :type text: bytes or unicode
+        """
+
+        # if there's highlighted text, it'll get replaced by the new text
+        text = self._normalize_to_caption(text)
+        if self.highlight:
+            start, stop = self.highlight
+            btext, etext = self.edit_text[:start], self.edit_text[stop:]
+            result_text = btext + etext
+            result_pos = start
+        else:
+            result_text = self.edit_text
+            result_pos = self.edit_pos
+
+        try:
+            result_text = result_text[:result_pos] + text + result_text[result_pos:]
+        except (IndexError, TypeError) as exc:
+            raise ValueError(repr((self.edit_text, result_text, text))).with_traceback(exc.__traceback__) from exc
+
+        result_pos += len(text)
+        return (result_text, result_pos)
+
+    def keypress(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """
+        Handle editing keystrokes, return others.
+
+        >>> e, size = Edit(), (20,)
+        >>> e.keypress(size, "x")
+        >>> e.keypress(size, "left")
+        >>> e.keypress(size, "1")
+        >>> print(e.edit_text)
+        1x
+        >>> e.keypress(size, "backspace")
+        >>> e.keypress(size, "end")
+        >>> e.keypress(size, "2")
+        >>> print(e.edit_text)
+        x2
+        >>> e.keypress(size, "shift f1")
+        'shift f1'
+        """
+        pos = self.edit_pos
+        if self.valid_char(key):
+            if isinstance(key, str) and not isinstance(self._caption, str):
+                key = key.encode("utf-8")
+            self.insert_text(key)
+            return None
+
+        if key == "tab" and self.allow_tab:
+            key = " " * (8 - (self.edit_pos % 8))
+            self.insert_text(key)
+            return None
+
+        if key == "enter" and self.multiline:
+            key = "\n"
+            self.insert_text(key)
+            return None
+
+        if self._command_map[key] == Command.LEFT:
+            if pos == 0:
+                return key
+            pos = move_prev_char(self.edit_text, 0, pos)
+            self.set_edit_pos(pos)
+            return None
+
+        if self._command_map[key] == Command.RIGHT:
+            if pos >= len(self.edit_text):
+                return key
+            pos = move_next_char(self.edit_text, pos, len(self.edit_text))
+            self.set_edit_pos(pos)
+            return None
+
+        if self._command_map[key] in {Command.UP, Command.DOWN}:
+            self.highlight = None
+
+            _x, y = self.get_cursor_coords(size)
+            pref_col = self.get_pref_col(size)
+            if pref_col is None:
+                raise ValueError(pref_col)
+
+            # if pref_col is None:
+            #    pref_col = x
+
+            if self._command_map[key] == Command.UP:
+                y -= 1
+            else:
+                y += 1
+
+            if not self.move_cursor_to_coords(size, pref_col, y):
+                return key
+            return None
+
+        if key == "backspace":
+            self.pref_col_maxcol = None, None
+            if not self._delete_highlighted():
+                if pos == 0:
+                    return key
+                pos = move_prev_char(self.edit_text, 0, pos)
+                self.set_edit_text(self.edit_text[:pos] + self.edit_text[self.edit_pos :])
+                self.set_edit_pos(pos)
+                return None
+            return None
+
+        if key == "delete":
+            self.pref_col_maxcol = None, None
+            if not self._delete_highlighted():
+                if pos >= len(self.edit_text):
+                    return key
+                pos = move_next_char(self.edit_text, pos, len(self.edit_text))
+                self.set_edit_text(self.edit_text[: self.edit_pos] + self.edit_text[pos:])
+                return None
+            return None
+
+        if self._command_map[key] in {Command.MAX_LEFT, Command.MAX_RIGHT}:
+            self.highlight = None
+            self.pref_col_maxcol = None, None
+
+            _x, y = self.get_cursor_coords(size)
+
+            if self._command_map[key] == Command.MAX_LEFT:
+                self.move_cursor_to_coords(size, Align.LEFT, y)
+            else:
+                self.move_cursor_to_coords(size, Align.RIGHT, y)
+            return None
+
+        # key wasn't handled
+        return key
+
+    def move_cursor_to_coords(
+        self,
+        size: tuple[int],
+        x: int | Literal[Align.LEFT, Align.RIGHT],
+        y: int,
+    ) -> bool:
+        """
+        Set the cursor position with (x,y) coordinates.
+        Returns True if move succeeded, False otherwise.
+
+        >>> size = (10,)
+        >>> e = Edit("", "edit\\ntext")
+        >>> e.move_cursor_to_coords(size, 5, 0)
+        True
+        >>> e.edit_pos
+        4
+        >>> e.move_cursor_to_coords(size, 5, 3)
+        False
+        >>> e.move_cursor_to_coords(size, 0, 1)
+        True
+        >>> e.edit_pos
+        5
+        """
+        (maxcol,) = size
+        trans = self.get_line_translation(maxcol)
+        _top_x, top_y = self.position_coords(maxcol, 0)
+        if y < top_y or y >= len(trans):
+            return False
+
+        pos = text_layout.calc_pos(self.get_text()[0], trans, x, y)
+        e_pos = min(max(pos - len(self.caption), 0), len(self.edit_text))
+        self.edit_pos = e_pos
+        self.pref_col_maxcol = x, maxcol
+        self._invalidate()
+        return True
+
+    def mouse_event(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """
+        Move the cursor to the location clicked for button 1.
+
+        >>> size = (20,)
+        >>> e = Edit("", "words here")
+        >>> e.mouse_event(size, "mouse press", 1, 2, 0, True)
+        True
+        >>> e.edit_pos
+        2
+        """
+        if button == 1:
+            return self.move_cursor_to_coords(size, col, row)
+        return False
+
+    def _delete_highlighted(self) -> bool:
+        """
+        Delete all highlighted text and update cursor position, if any
+        text is highlighted.
+        """
+        if not self.highlight:
+            return False
+        start, stop = self.highlight
+        btext, etext = self.edit_text[:start], self.edit_text[stop:]
+        self.set_edit_text(btext + etext)
+        self.edit_pos = start
+        self.highlight = None
+        return True
+
+    def render(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> TextCanvas | CompositeCanvas:
+        """
+        Render edit widget and return canvas.  Include cursor when in
+        focus.
+
+        >>> edit = Edit("? ", "yes")
+        >>> c = edit.render((10,), focus=True)
+        >>> c.text
+        [b'? yes     ']
+        >>> c.cursor
+        (5, 0)
+        """
+        self._shift_view_to_cursor = bool(focus)
+
+        canv: TextCanvas | CompositeCanvas = super().render(size, focus)
+        if focus:
+            canv = CompositeCanvas(canv)
+            canv.cursor = self.get_cursor_coords(size)
+
+        # .. will need to FIXME if I want highlight to work again
+        # if self.highlight:
+        #    hstart, hstop = self.highlight_coords()
+        #    d.coords['highlight'] = [ hstart, hstop ]
+        return canv
+
+    def get_line_translation(
+        self,
+        maxcol: int,
+        ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None = None,
+    ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]:
+        trans = super().get_line_translation(maxcol, ta)
+        if not self._shift_view_to_cursor:
+            return trans
+
+        text, _ignore = self.get_text()
+        x, y = text_layout.calc_coords(text, trans, self.edit_pos + len(self.caption))
+        if x < 0:
+            return [
+                *trans[:y],
+                *[text_layout.shift_line(trans[y], -x)],
+                *trans[y + 1 :],
+            ]
+
+        if x >= maxcol:
+            return [
+                *trans[:y],
+                *[text_layout.shift_line(trans[y], -(x - maxcol + 1))],
+                *trans[y + 1 :],
+            ]
+
+        return trans
+
+    def get_cursor_coords(self, size: tuple[int]) -> tuple[int, int]:
+        """
+        Return the (*x*, *y*) coordinates of cursor within widget.
+
+        >>> Edit("? ", "yes").get_cursor_coords((10,))
+        (5, 0)
+        """
+        (maxcol,) = size
+
+        self._shift_view_to_cursor = True
+        return self.position_coords(maxcol, self.edit_pos)
+
+    def position_coords(self, maxcol: int, pos: int) -> tuple[int, int]:
+        """
+        Return (*x*, *y*) coordinates for an offset into self.edit_text.
+        """
+
+        p = pos + len(self.caption)
+        trans = self.get_line_translation(maxcol)
+        x, y = text_layout.calc_coords(self.get_text()[0], trans, p)
+        return x, y
+
+
+class IntEdit(Edit):
+    """Edit widget for integer values"""
+
+    def valid_char(self, ch: str) -> bool:
+        """
+        Return true for decimal digits.
+        """
+        return len(ch) == 1 and ch in string.digits
+
+    def __init__(self, caption="", default: int | str | None = None) -> None:
+        """
+        caption -- caption markup
+        default -- default edit value
+
+        >>> IntEdit("", 42)
+        
+        """
+        if default is not None:
+            val = str(default)
+        else:
+            val = ""
+        super().__init__(caption, val)
+
+    def keypress(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """
+        Handle editing keystrokes.  Remove leading zeros.
+
+        >>> e, size = IntEdit("", 5002), (10,)
+        >>> e.keypress(size, "home")
+        >>> e.keypress(size, "delete")
+        >>> print(e.edit_text)
+        002
+        >>> e.keypress(size, "end")
+        >>> print(e.edit_text)
+        2
+        """
+        if unhandled := super().keypress(size, key):
+            return unhandled
+
+        # trim leading zeros
+        while self.edit_pos > 0 and self.edit_text[:1] == "0":
+            self.set_edit_pos(self.edit_pos - 1)
+            self.set_edit_text(self.edit_text[1:])
+
+        return None
+
+    def value(self) -> int:
+        """
+        Return the numeric value of self.edit_text.
+
+        >>> e, size = IntEdit(), (10,)
+        >>> e.keypress(size, "5")
+        >>> e.keypress(size, "1")
+        >>> e.value() == 51
+        True
+        """
+        if self.edit_text:
+            return int(self.edit_text)
+
+        return 0
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/filler.py b/python/user_packages/Python313/site-packages/urwid/widget/filler.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf03cbb48ae29dd7192478f973fd03e36697756b
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/filler.py
@@ -0,0 +1,410 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from urwid.canvas import CompositeCanvas
+from urwid.split_repr import remove_defaults
+from urwid.util import int_scale
+
+from .constants import (
+    RELATIVE_100,
+    Sizing,
+    VAlign,
+    WHSettings,
+    normalize_height,
+    normalize_valign,
+    simplify_height,
+    simplify_valign,
+)
+from .widget_decoration import WidgetDecoration, WidgetError
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class FillerError(WidgetError):
+    pass
+
+
+class Filler(WidgetDecoration[WrappedWidget]):
+    def __init__(
+        self,
+        body: WrappedWidget,
+        valign: (
+            Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int]
+        ) = VAlign.MIDDLE,
+        height: (
+            int | Literal["pack", WHSettings.PACK] | tuple[Literal["relative", WHSettings.RELATIVE], int] | None
+        ) = WHSettings.PACK,
+        min_height: int | None = None,
+        top: int = 0,
+        bottom: int = 0,
+    ) -> None:
+        """
+        :param body: a flow widget or box widget to be filled around (stored as self.original_widget)
+        :type body: Widget
+
+        :param valign: one of:
+            ``'top'``, ``'middle'``, ``'bottom'``,
+            (``'relative'``, *percentage* 0=top 100=bottom)
+
+        :param height: one of:
+
+            ``'pack'``
+              if body is a flow widget
+
+            *given height*
+              integer number of rows for self.original_widget
+
+            (``'relative'``, *percentage of total height*)
+              make height depend on container's height
+
+        :param min_height: one of:
+
+            ``None``
+              if no minimum or if body is a flow widget
+
+            *minimum height*
+              integer number of rows for the widget when height not fixed
+
+        :param top: a fixed number of rows to fill at the top
+        :type top: int
+        :param bottom: a fixed number of rows to fill at the bottom
+        :type bottom: int
+
+        If body is a flow widget, then height must be ``'pack'`` and *min_height* will be ignored.
+        Sizing of the filler will be BOX/FLOW in this case.
+
+        If height is integer, *min_height* will be ignored and sizing of filler will be BOX/FLOW.
+
+        Filler widgets will try to satisfy height argument first by reducing the valign amount when necessary.
+        If height still cannot be satisfied it will also be reduced.
+        """
+        super().__init__(body)
+
+        # convert old parameters to the new top/bottom values
+        if isinstance(height, tuple):
+            if height[0] == "fixed top":
+                if not isinstance(valign, tuple) or valign[0] != "fixed bottom":
+                    raise FillerError("fixed top height may only be used with fixed bottom valign")
+                top = height[1]
+                height = RELATIVE_100
+            elif height[0] == "fixed bottom":
+                if not isinstance(valign, tuple) or valign[0] != "fixed top":
+                    raise FillerError("fixed bottom height may only be used with fixed top valign")
+                bottom = height[1]
+                height = RELATIVE_100
+
+        if isinstance(valign, tuple):
+            if valign[0] == "fixed top":
+                top = valign[1]
+                normalized_valign = VAlign.TOP
+            elif valign[0] == "fixed bottom":
+                bottom = valign[1]
+                normalized_valign = VAlign.BOTTOM
+            else:
+                normalized_valign = valign
+
+        elif not isinstance(valign, (VAlign, str)):
+            raise FillerError(f"invalid valign: {valign!r}")
+
+        else:
+            normalized_valign = VAlign(valign)
+
+        # convert old flow mode parameter height=None to height='flow'
+        if height is None or height == Sizing.FLOW:
+            height = WHSettings.PACK
+
+        self.top = top
+        self.bottom = bottom
+        self.valign_type, self.valign_amount = normalize_valign(normalized_valign, FillerError)
+        self.height_type, self.height_amount = normalize_height(height, FillerError)
+
+        if self.height_type not in {WHSettings.GIVEN, WHSettings.PACK}:
+            self.min_height = min_height
+        else:
+            self.min_height = None
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Widget sizing.
+
+        Sizing BOX is always supported.
+        Sizing FLOW is supported if: FLOW widget (a height type is PACK) or BOX widget with height GIVEN
+        """
+        sizing: set[Sizing] = {Sizing.BOX}
+        if self.height_type in {WHSettings.PACK, WHSettings.GIVEN}:
+            sizing.add(Sizing.FLOW)
+        return frozenset(sizing)
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """Flow pack support if FLOW sizing supported."""
+        if self.height_type == WHSettings.PACK:
+            return self.original_widget.rows(size, focus) + self.top + self.bottom
+        if self.height_type == WHSettings.GIVEN:
+            return self.height_amount + self.top + self.bottom
+        raise FillerError("Method 'rows' not supported for BOX widgets")  # pragma: no cover
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "valign": simplify_valign(self.valign_type, self.valign_amount),
+            "height": simplify_height(self.height_type, self.height_amount),
+            "top": self.top,
+            "bottom": self.bottom,
+            "min_height": self.min_height,
+        }
+        return remove_defaults(attrs, Filler.__init__)
+
+    @property
+    def body(self) -> WrappedWidget:
+        """backwards compatibility, widget used to be stored as body"""
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as body. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.original_widget
+
+    @body.setter
+    def body(self, new_body: WrappedWidget) -> None:
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as body. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.original_widget = new_body
+
+    def get_body(self) -> WrappedWidget:
+        """backwards compatibility, widget used to be stored as body"""
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as body. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.original_widget
+
+    def set_body(self, new_body: WrappedWidget) -> None:
+        warnings.warn(
+            "backwards compatibility, widget used to be stored as body. API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.original_widget = new_body
+
+    def selectable(self) -> bool:
+        """Return selectable from body."""
+        return self._original_widget.selectable()
+
+    def filler_values(self, size: tuple[int, int] | tuple[int], focus: bool) -> tuple[int, int]:
+        """
+        Return the number of rows to pad on the top and bottom.
+
+        Override this method to define custom padding behaviour.
+        """
+        maxcol, maxrow = self.pack(size, focus)
+
+        if self.height_type == WHSettings.PACK:
+            height = self._original_widget.rows((maxcol,), focus=focus)
+            return calculate_top_bottom_filler(
+                maxrow,
+                self.valign_type,
+                self.valign_amount,
+                WHSettings.GIVEN,
+                height,
+                None,
+                self.top,
+                self.bottom,
+            )
+
+        return calculate_top_bottom_filler(
+            maxrow,
+            self.valign_type,
+            self.valign_amount,
+            self.height_type,
+            self.height_amount,
+            self.min_height,
+            self.top,
+            self.bottom,
+        )
+
+    def render(
+        self,
+        size: tuple[int, int] | tuple[int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        """Render self.original_widget with space above and/or below."""
+        maxcol, maxrow = self.pack(size, focus)
+        top, bottom = self.filler_values(size, focus)
+
+        if self.height_type == WHSettings.PACK:
+            canv = self._original_widget.render((maxcol,), focus)
+        else:
+            canv = self._original_widget.render((maxcol, maxrow - top - bottom), focus)
+        canv = CompositeCanvas(canv)
+
+        if maxrow and canv.rows() > maxrow and canv.cursor is not None:
+            _cx, cy = canv.cursor
+            if cy >= maxrow:
+                canv.trim(cy - maxrow + 1, maxrow - top - bottom)
+        if canv.rows() > maxrow:
+            canv.trim(0, maxrow)
+            return canv
+        canv.pad_trim_top_bottom(top, bottom)
+        return canv
+
+    def keypress(
+        self,
+        size: tuple[int, int] | tuple[()],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """Pass keypress to self.original_widget."""
+        maxcol, maxrow = self.pack(size, True)
+        if self.height_type == WHSettings.PACK:
+            return self._original_widget.keypress((maxcol,), key)
+
+        top, bottom = self.filler_values((maxcol, maxrow), True)
+        return self._original_widget.keypress((maxcol, maxrow - top - bottom), key)
+
+    def get_cursor_coords(self, size: tuple[int, int] | tuple[int]) -> tuple[int, int] | None:
+        """Return cursor coords from self.original_widget if any."""
+        maxcol, maxrow = self.pack(size, True)
+        if not hasattr(self._original_widget, "get_cursor_coords"):
+            return None
+
+        top, bottom = self.filler_values(size, True)
+        if self.height_type == WHSettings.PACK:
+            coords = self._original_widget.get_cursor_coords((maxcol,))
+        else:
+            coords = self._original_widget.get_cursor_coords((maxcol, maxrow - top - bottom))
+        if not coords:
+            return None
+        x, y = coords
+        if y >= maxrow:
+            y = maxrow - 1
+        return x, y + top
+
+    def get_pref_col(self, size: tuple[int, int] | tuple[int]) -> int | None:
+        """Return pref_col from self.original_widget if any."""
+        maxcol, maxrow = self.pack(size, True)
+        if not hasattr(self._original_widget, "get_pref_col"):
+            return None
+
+        if self.height_type == WHSettings.PACK:
+            x = self._original_widget.get_pref_col((maxcol,))
+        else:
+            top, bottom = self.filler_values(size, True)
+            x = self._original_widget.get_pref_col((maxcol, maxrow - top - bottom))
+
+        return x
+
+    def move_cursor_to_coords(self, size: tuple[int, int] | tuple[int], col: int, row: int) -> bool:
+        """Pass to self.original_widget."""
+        maxcol, maxrow = self.pack(size, True)
+        if not hasattr(self._original_widget, "move_cursor_to_coords"):
+            return True
+
+        top, bottom = self.filler_values(size, True)
+        if row < top or row >= maxcol - bottom:
+            return False
+
+        if self.height_type == WHSettings.PACK:
+            return self._original_widget.move_cursor_to_coords((maxcol,), col, row - top)
+        return self._original_widget.move_cursor_to_coords((maxcol, maxrow - top - bottom), col, row - top)
+
+    def mouse_event(
+        self,
+        size: tuple[int, int] | tuple[int],  # type: ignore[override]
+        event,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """Pass to self.original_widget."""
+        maxcol, maxrow = self.pack(size, focus)
+        if not hasattr(self._original_widget, "mouse_event"):
+            return False
+
+        top, bottom = self.filler_values(size, True)
+        if row < top or row >= maxrow - bottom:
+            return False
+
+        if self.height_type == WHSettings.PACK:
+            return self._original_widget.mouse_event((maxcol,), event, button, col, row - top, focus)
+        return self._original_widget.mouse_event((maxcol, maxrow - top - bottom), event, button, col, row - top, focus)
+
+
+def calculate_top_bottom_filler(
+    maxrow: int,
+    valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign,
+    valign_amount: int,
+    height_type: Literal["given", "relative", "clip", WHSettings.GIVEN, WHSettings.RELATIVE, WHSettings.CLIP],
+    height_amount: int,
+    min_height: int | None,
+    top: int,
+    bottom: int,
+) -> tuple[int, int]:
+    """
+    Return the amount of filler (or clipping) on the top and
+    bottom part of maxrow rows to satisfy the following:
+
+    valign_type -- 'top', 'middle', 'bottom', 'relative'
+    valign_amount -- a percentage when align_type=='relative'
+    height_type -- 'given', 'relative', 'clip'
+    height_amount -- a percentage when width_type=='relative'
+        otherwise equal to the height of the widget
+    min_height -- a desired minimum width for the widget or None
+    top -- a fixed number of rows to fill on the top
+    bottom -- a fixed number of rows to fill on the bottom
+
+    >>> ctbf = calculate_top_bottom_filler
+    >>> ctbf(15, "top", 0, "given", 10, None, 2, 0)
+    (2, 3)
+    >>> ctbf(15, "relative", 0, "given", 10, None, 2, 0)
+    (2, 3)
+    >>> ctbf(15, "relative", 100, "given", 10, None, 2, 0)
+    (5, 0)
+    >>> ctbf(15, "middle", 0, "given", 4, None, 2, 0)
+    (6, 5)
+    >>> ctbf(15, "middle", 0, "given", 18, None, 2, 0)
+    (0, 0)
+    >>> ctbf(20, "top", 0, "relative", 60, None, 0, 0)
+    (0, 8)
+    >>> ctbf(20, "relative", 30, "relative", 60, None, 0, 0)
+    (2, 6)
+    >>> ctbf(20, "relative", 30, "relative", 60, 14, 0, 0)
+    (2, 4)
+    """
+    if height_type == WHSettings.RELATIVE:
+        maxheight = max(maxrow - top - bottom, 0)
+        height = int_scale(height_amount, 101, maxheight + 1)
+        if min_height is not None:
+            height = max(height, min_height)
+    else:
+        height = height_amount
+
+    valign = {VAlign.TOP: 0, VAlign.MIDDLE: 50, VAlign.BOTTOM: 100}.get(valign_type, valign_amount)
+
+    # add the remainder of top/bottom to the filler
+    filler = maxrow - height - top - bottom
+    bottom += int_scale(100 - valign, 101, filler + 1)
+    top = maxrow - height - bottom
+
+    # reduce filler if we are clipping an edge
+    if bottom < 0 < top:
+        shift = min(top, -bottom)
+        top -= shift
+        bottom += shift
+    elif top < 0 < bottom:
+        shift = min(bottom, -top)
+        bottom -= shift
+        top += shift
+
+    # no negative values for filler at the moment
+    top = max(top, 0)
+    bottom = max(bottom, 0)
+
+    return top, bottom
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/frame.py b/python/user_packages/Python313/site-packages/urwid/widget/frame.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e4e3f4cf546003bc4f732d31b825f18004100ea
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/frame.py
@@ -0,0 +1,605 @@
+from __future__ import annotations
+
+import typing
+import warnings
+from collections.abc import MutableMapping
+
+from urwid.canvas import CanvasCombine, CompositeCanvas
+from urwid.split_repr import remove_defaults
+from urwid.util import is_mouse_press
+
+from .constants import Sizing, VAlign
+from .container import WidgetContainerMixin
+from .filler import Filler
+from .widget import Widget, WidgetError
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterator
+
+    from typing_extensions import Literal
+
+
+BodyWidget = typing.TypeVar("BodyWidget")
+HeaderWidget = typing.TypeVar("HeaderWidget")
+FooterWidget = typing.TypeVar("FooterWidget")
+
+
+class FrameError(WidgetError):
+    pass
+
+
+def _check_widget_subclass(widget: Widget | None) -> None:
+    if widget is None:
+        return
+
+    if not isinstance(widget, Widget):
+        obj_class_path = f"{widget.__class__.__module__}.{widget.__class__.__name__}"
+        warnings.warn(
+            f"{obj_class_path} is not subclass of Widget",
+            DeprecationWarning,
+            stacklevel=3,
+        )
+
+
+class Frame(Widget, WidgetContainerMixin, typing.Generic[BodyWidget, HeaderWidget, FooterWidget]):
+    """
+    Frame widget is a box widget with optional header and footer
+    flow widgets placed above and below the box widget.
+
+    .. note:: The main difference between a Frame and a :class:`Pile` widget
+        defined as: `Pile([('pack', header), body, ('pack', footer)])` is that
+        the Frame will not automatically change focus up and down in response to keystrokes.
+    """
+
+    _selectable = True
+    _sizing = frozenset([Sizing.BOX])
+
+    def __init__(
+        self,
+        body: BodyWidget,
+        header: HeaderWidget = None,
+        footer: FooterWidget = None,
+        focus_part: Literal["header", "footer", "body"] | Widget = "body",
+    ):
+        """
+        :param body: a box widget for the body of the frame
+        :type body: Widget
+        :param header: a flow widget for above the body (or None)
+        :type header: Widget
+        :param footer: a flow widget for below the body (or None)
+        :type footer: Widget
+        :param focus_part:  'header', 'footer' or 'body'
+        :type focus_part: str | Widget
+        """
+        super().__init__()
+
+        self._header = header
+        self._body = body
+        self._footer = footer
+        if focus_part in {"header", "footer", "body"}:
+            self.focus_part = focus_part
+        elif focus_part == header:
+            self.focus_part = "header"
+        elif focus_part == footer:
+            self.focus_part = "footer"
+        elif focus_part == body:
+            self.focus_part = "body"
+        else:
+            raise ValueError(f"Invalid focus part {focus_part!r}")
+
+        _check_widget_subclass(header)
+        _check_widget_subclass(body)
+        _check_widget_subclass(footer)
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "body": self._body,
+            "header": self._header,
+            "footer": self._footer,
+            "focus_part": self.focus_part,
+        }
+        return remove_defaults(attrs, Frame.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        yield "body", self._body
+        yield "header", self._header
+        yield "footer", self._footer
+        yield "focus_part", self.focus_part
+
+    @property
+    def header(self) -> HeaderWidget:
+        return self._header
+
+    @header.setter
+    def header(self, header: HeaderWidget) -> None:
+        _check_widget_subclass(header)
+        self._header = header
+        if header is None and self.focus_part == "header":
+            self.focus_part = "body"
+        self._invalidate()
+
+    def get_header(self) -> HeaderWidget:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.get_header` is deprecated, "
+            f"standard property `{self.__class__.__name__}.header` should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.header
+
+    def set_header(self, header: HeaderWidget) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.set_header` is deprecated, "
+            f"standard property `{self.__class__.__name__}.header` should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.header = header
+
+    @property
+    def body(self) -> BodyWidget:
+        return self._body
+
+    @body.setter
+    def body(self, body: BodyWidget) -> None:
+        _check_widget_subclass(body)
+        self._body = body
+        self._invalidate()
+
+    def get_body(self) -> BodyWidget:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.get_body` is deprecated, "
+            f"standard property {self.__class__.__name__}.body should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.body
+
+    def set_body(self, body: BodyWidget) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.set_body` is deprecated, "
+            f"standard property `{self.__class__.__name__}.body` should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.body = body
+
+    @property
+    def footer(self) -> FooterWidget:
+        return self._footer
+
+    @footer.setter
+    def footer(self, footer: FooterWidget) -> None:
+        _check_widget_subclass(footer)
+        self._footer = footer
+        if footer is None and self.focus_part == "footer":
+            self.focus_part = "body"
+        self._invalidate()
+
+    def get_footer(self) -> FooterWidget:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.get_footer` is deprecated, "
+            f"standard property `{self.__class__.__name__}.footer` should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.footer
+
+    def set_footer(self, footer: FooterWidget) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}.set_footer` is deprecated, "
+            f"standard property `{self.__class__.__name__}.footer` should be used instead."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.footer = footer
+
+    @property
+    def focus_position(self) -> Literal["header", "footer", "body"]:
+        """
+        writeable property containing an indicator which part of the frame
+        that is in focus: `'body', 'header'` or `'footer'`.
+
+        :returns: one of 'header', 'footer' or 'body'.
+        :rtype: str
+        """
+        return self.focus_part
+
+    @focus_position.setter
+    def focus_position(self, part: Literal["header", "footer", "body"]) -> None:
+        """
+        Determine which part of the frame is in focus.
+
+        :param part: 'header', 'footer' or 'body'
+        :type part: str
+        """
+        if part not in {"header", "footer", "body"}:
+            raise IndexError(f"Invalid position for Frame: {part}")
+        if (part == "header" and self._header is None) or (part == "footer" and self._footer is None):
+            raise IndexError(f"This Frame has no {part}")
+        self.focus_part = part
+        self._invalidate()
+
+    def get_focus(self) -> Literal["header", "footer", "body"]:
+        """
+        writeable property containing an indicator which part of the frame
+        that is in focus: `'body', 'header'` or `'footer'`.
+
+        .. note:: included for backwards compatibility. You should rather use
+            the container property :attr:`.focus_position` to get this value.
+
+        :returns: one of 'header', 'footer' or 'body'.
+        :rtype: str
+        """
+        warnings.warn(
+            "included for backwards compatibility."
+            "You should rather use the container property `.focus_position` to get this value."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.focus_position
+
+    def set_focus(self, part: Literal["header", "footer", "body"]) -> None:
+        warnings.warn(
+            "included for backwards compatibility."
+            "You should rather use the container property `.focus_position` to set this value."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.focus_position = part
+
+    @property
+    def focus(self) -> BodyWidget | HeaderWidget | FooterWidget:
+        """
+        child :class:`Widget` in focus: the body, header or footer widget.
+        This is a read-only property."""
+        return {"header": self._header, "footer": self._footer, "body": self._body}[self.focus_part]
+
+    @property
+    def contents(
+        self,
+    ) -> MutableMapping[
+        Literal["header", "footer", "body"],
+        tuple[BodyWidget | HeaderWidget | FooterWidget, None],
+    ]:
+        """
+        a dict-like object similar to::
+
+            {
+                "body": (body_widget, None),
+                "header": (header_widget, None),  # if frame has a header
+                "footer": (footer_widget, None),  # if frame has a footer
+            }
+
+        This object may be used to read or update the contents of the Frame.
+
+        The values are similar to the list-like .contents objects used
+        in other containers with (:class:`Widget`, options) tuples, but are
+        constrained to keys for each of the three usual parts of a Frame.
+        When other keys are used a :exc:`KeyError` will be raised.
+
+        Currently, all options are `None`, but using the :meth:`options` method
+        to create the options value is recommended for forwards
+        compatibility.
+        """
+
+        # noinspection PyMethodParameters
+        class FrameContents(
+            MutableMapping[
+                str,
+                tuple[typing.Union[BodyWidget, HeaderWidget, FooterWidget], None],
+            ]
+        ):
+            # pylint: disable=no-self-argument
+
+            __slots__ = ()
+
+            def __len__(inner_self) -> int:
+                return len(inner_self.keys())
+
+            __getitem__ = self._contents__getitem__
+            __setitem__ = self._contents__setitem__
+            __delitem__ = self._contents__delitem__
+
+            def __iter__(inner_self) -> Iterator[str]:
+                yield from inner_self.keys()
+
+            def __repr__(inner_self) -> str:
+                return f"<{inner_self.__class__.__name__}({dict(inner_self)}) for {self}>"
+
+            def __rich_repr__(inner_self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+                yield from inner_self.items()
+
+        return FrameContents()
+
+    def _contents_keys(self) -> list[Literal["header", "footer", "body"]]:
+        keys = ["body"]
+        if self._header:
+            keys.append("header")
+        if self._footer:
+            keys.append("footer")
+        return keys
+
+    @typing.overload
+    def _contents__getitem__(self, key: Literal["body"]) -> tuple[BodyWidget, None]: ...
+
+    @typing.overload
+    def _contents__getitem__(self, key: Literal["header"]) -> tuple[HeaderWidget, None]: ...
+
+    @typing.overload
+    def _contents__getitem__(self, key: Literal["footer"]) -> tuple[FooterWidget, None]: ...
+
+    def _contents__getitem__(
+        self, key: Literal["body", "header", "footer"]
+    ) -> tuple[BodyWidget | HeaderWidget | FooterWidget, None]:
+        if key == "body":
+            return (self._body, None)
+        if key == "header" and self._header:
+            return (self._header, None)
+        if key == "footer" and self._footer:
+            return (self._footer, None)
+        raise KeyError(f"Frame.contents has no key: {key!r}")
+
+    @typing.overload
+    def _contents__setitem__(self, key: Literal["body"], value: tuple[BodyWidget, None]) -> None: ...
+
+    @typing.overload
+    def _contents__setitem__(self, key: Literal["header"], value: tuple[HeaderWidget, None]) -> None: ...
+
+    @typing.overload
+    def _contents__setitem__(self, key: Literal["footer"], value: tuple[FooterWidget, None]) -> None: ...
+
+    def _contents__setitem__(
+        self,
+        key: Literal["body", "header", "footer"],
+        value: tuple[BodyWidget | HeaderWidget | FooterWidget, None],
+    ) -> None:
+        if key not in {"body", "header", "footer"}:
+            raise KeyError(f"Frame.contents has no key: {key!r}")
+        try:
+            value_w, value_options = value
+            if value_options is not None:
+                raise FrameError(f"added content invalid: {value!r}")
+        except (ValueError, TypeError) as exc:
+            raise FrameError(f"added content invalid: {value!r}").with_traceback(exc.__traceback__) from exc
+        if key == "body":
+            self.body = value_w
+        elif key == "footer":
+            self.footer = value_w
+        else:
+            self.header = value_w
+
+    def _contents__delitem__(self, key: Literal["header", "footer"]) -> None:
+        if key not in {"header", "footer"}:
+            raise KeyError(f"Frame.contents can't remove key: {key!r}")
+        if (key == "header" and self._header is None) or (key == "footer" and self._footer is None):
+            raise KeyError(f"Frame.contents has no key: {key!r}")
+        if key == "header":
+            self.header = None
+        else:
+            self.footer = None
+
+    def options(self) -> None:
+        """
+        There are currently no options for Frame contents.
+
+        Return None as a placeholder for future options.
+        """
+
+    def frame_top_bottom(self, size: tuple[int, int], focus: bool) -> tuple[tuple[int, int], tuple[int, int]]:
+        """
+        Calculate the number of rows for the header and footer.
+
+        :param size: See :meth:`Widget.render` for details
+        :type size: widget size
+        :param focus: ``True`` if this widget is in focus
+        :type focus: bool
+        :returns: `(head rows, foot rows),(orig head, orig foot)`
+                  orig head/foot are from rows() calls.
+        :rtype: (int, int), (int, int)
+        """
+        (maxcol, maxrow) = size
+        frows = hrows = 0
+
+        if self.header:
+            hrows = self.header.rows((maxcol,), self.focus_part == "header" and focus)
+
+        if self.footer:
+            frows = self.footer.rows((maxcol,), self.focus_part == "footer" and focus)
+
+        remaining = maxrow
+
+        if self.focus_part == "footer":
+            if frows >= remaining:
+                return (0, remaining), (hrows, frows)
+
+            remaining -= frows
+            if hrows >= remaining:
+                return (remaining, frows), (hrows, frows)
+
+        elif self.focus_part == "header":
+            if hrows >= maxrow:
+                return (remaining, 0), (hrows, frows)
+
+            remaining -= hrows
+            if frows >= remaining:
+                return (hrows, remaining), (hrows, frows)
+
+        elif hrows + frows >= remaining:
+            # self.focus_part == 'body'
+            rless1 = max(0, remaining - 1)
+            if frows >= remaining - 1:
+                return (0, rless1), (hrows, frows)
+
+            remaining -= frows
+            rless1 = max(0, remaining - 1)
+            return (rless1, frows), (hrows, frows)
+
+        return (hrows, frows), (hrows, frows)
+
+    def render(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        (maxcol, maxrow) = size
+        (htrim, ftrim), (hrows, frows) = self.frame_top_bottom((maxcol, maxrow), focus)
+
+        combinelist = []
+        depends_on = []
+
+        head = None
+        if htrim and htrim < hrows:
+            head = Filler(self.header, VAlign.TOP).render((maxcol, htrim), focus and self.focus_part == "header")
+        elif htrim:
+            head = self.header.render((maxcol,), focus and self.focus_part == "header")
+            if head.rows() != hrows:
+                raise RuntimeError("rows, render mismatch")
+        if head:
+            combinelist.append((head, "header", self.focus_part == "header"))
+            depends_on.append(self.header)
+
+        if ftrim + htrim < maxrow:
+            body = self.body.render((maxcol, maxrow - ftrim - htrim), focus and self.focus_part == "body")
+            combinelist.append((body, "body", self.focus_part == "body"))
+            depends_on.append(self.body)
+
+        foot = None
+        if ftrim and ftrim < frows:
+            foot = Filler(self.footer, VAlign.BOTTOM).render((maxcol, ftrim), focus and self.focus_part == "footer")
+        elif ftrim:
+            foot = self.footer.render((maxcol,), focus and self.focus_part == "footer")
+            if foot.rows() != frows:
+                raise RuntimeError("rows, render mismatch")
+        if foot:
+            combinelist.append((foot, "footer", self.focus_part == "footer"))
+            depends_on.append(self.footer)
+
+        return CanvasCombine(combinelist)
+
+    def keypress(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """Pass keypress to widget in focus."""
+        (maxcol, maxrow) = size
+
+        if self.focus_part == "header" and self.header is not None:
+            if not self.header.selectable():
+                return key
+            return self.header.keypress((maxcol,), key)
+        if self.focus_part == "footer" and self.footer is not None:
+            if not self.footer.selectable():
+                return key
+            return self.footer.keypress((maxcol,), key)
+        if self.focus_part != "body":
+            return key
+        remaining = maxrow
+        if self.header is not None:
+            remaining -= self.header.rows((maxcol,))
+        if self.footer is not None:
+            remaining -= self.footer.rows((maxcol,))
+        if remaining <= 0:
+            return key
+
+        if not self.body.selectable():
+            return key
+        return self.body.keypress((maxcol, remaining), key)
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """
+        Pass mouse event to appropriate part of frame.
+        Focus may be changed on button 1 press.
+        """
+        (maxcol, maxrow) = size
+        (htrim, ftrim), (_hrows, _frows) = self.frame_top_bottom((maxcol, maxrow), focus)
+
+        if row < htrim:  # within header
+            focus = focus and self.focus_part == "header"
+            if is_mouse_press(event) and button == 1 and self.header.selectable():
+                self.focus_position = "header"
+            if not hasattr(self.header, "mouse_event"):
+                return False
+            return self.header.mouse_event((maxcol,), event, button, col, row, focus)
+
+        if row >= maxrow - ftrim:  # within footer
+            focus = focus and self.focus_part == "footer"
+            if is_mouse_press(event) and button == 1 and self.footer.selectable():
+                self.focus_position = "footer"
+            if not hasattr(self.footer, "mouse_event"):
+                return False
+            return self.footer.mouse_event((maxcol,), event, button, col, row - maxrow + ftrim, focus)
+
+        # within body
+        focus = focus and self.focus_part == "body"
+        if is_mouse_press(event) and button == 1 and self.body.selectable():
+            self.focus_position = "body"
+
+        if not hasattr(self.body, "mouse_event"):
+            return False
+        return self.body.mouse_event((maxcol, maxrow - htrim - ftrim), event, button, col, row - htrim, focus)
+
+    def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None:
+        """Return the cursor coordinates of the focus widget."""
+        if not self.focus.selectable():
+            return None
+        if not hasattr(self.focus, "get_cursor_coords"):
+            return None
+
+        fp = self.focus_position
+        (maxcol, maxrow) = size
+        (hrows, frows), _ = self.frame_top_bottom(size, True)
+
+        if fp == "header":
+            row_adjust = 0
+            coords = self.header.get_cursor_coords((maxcol,))
+        elif fp == "body":
+            row_adjust = hrows
+            coords = self.body.get_cursor_coords((maxcol, maxrow - hrows - frows))
+        else:
+            row_adjust = maxrow - frows
+            coords = self.footer.get_cursor_coords((maxcol,))
+
+        if coords is None:
+            return None
+
+        x, y = coords
+        return x, y + row_adjust
+
+    def __iter__(self) -> Iterator[Literal["header", "body", "footer"]]:
+        """
+        Return an iterator over the positions in this Frame top to bottom.
+        """
+        if self._header:
+            yield "header"
+        yield "body"
+        if self._footer:
+            yield "footer"
+
+    def __reversed__(self) -> Iterator[Literal["footer", "body", "header"]]:
+        """
+        Return an iterator over the positions in this Frame bottom to top.
+        """
+        if self._footer:
+            yield "footer"
+        yield "body"
+        if self._header:
+            yield "header"
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/grid_flow.py b/python/user_packages/Python313/site-packages/urwid/widget/grid_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..e15af7725b737733e6dc00dfed938a6b65ea827f
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/grid_flow.py
@@ -0,0 +1,517 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from urwid.split_repr import remove_defaults
+
+from .columns import Columns
+from .constants import Align, Sizing, WHSettings
+from .container import WidgetContainerListContentsMixin, WidgetContainerMixin
+from .divider import Divider
+from .monitored_list import MonitoredFocusList, MonitoredList
+from .padding import Padding
+from .pile import Pile
+from .widget import Widget, WidgetError, WidgetWarning, WidgetWrap
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterable, Iterator, Sequence
+
+    from typing_extensions import Literal
+
+
+class GridFlowError(WidgetError):
+    """GridFlow specific error."""
+
+
+class GridFlowWarning(WidgetWarning):
+    """GridFlow specific warning."""
+
+
+class GridFlow(WidgetWrap[Pile], WidgetContainerMixin, WidgetContainerListContentsMixin):
+    """
+    The GridFlow widget is a flow widget that renders all the widgets it contains the same width,
+    and it arranges them from left to right and top to bottom.
+    """
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Widget sizing.
+
+        ..note:: Empty widget sizing is limited to the FLOW due to no data for width.
+        """
+        if self:
+            return frozenset((Sizing.FLOW, Sizing.FIXED))
+        return frozenset((Sizing.FLOW,))
+
+    def __init__(
+        self,
+        cells: Iterable[Widget],
+        cell_width: int,
+        h_sep: int,
+        v_sep: int,
+        align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int],
+        focus: int | Widget | None = None,
+    ) -> None:
+        """
+        :param cells: iterable of flow widgets to display
+        :param cell_width: column width for each cell
+        :param h_sep: blank columns between each cell horizontally
+        :param v_sep: blank rows between cells vertically
+            (if more than one row is required to display all the cells)
+        :param align: horizontal alignment of cells, one of:
+            'left', 'center', 'right', ('relative', percentage 0=left 100=right)
+        :param focus: widget index or widget instance to focus on
+        """
+        prepared_contents: list[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]] = []
+        focus_position: int = -1
+
+        for idx, widget in enumerate(cells):
+            prepared_contents.append((widget, (WHSettings.GIVEN, cell_width)))
+            if focus_position < 0 and (focus in {widget, idx} or (focus is None and widget.selectable())):
+                focus_position = idx
+
+        focus_position = max(focus_position, 0)
+
+        self._contents: MonitoredFocusList[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]] = MonitoredFocusList(
+            prepared_contents, focus=focus_position
+        )
+        self._contents.set_modified_callback(self._invalidate)
+        self._contents.set_focus_changed_callback(lambda f: self._invalidate())
+        self._contents.set_validate_contents_modified(self._contents_modified)
+        self._cell_width = cell_width
+        self.h_sep = h_sep
+        self.v_sep = v_sep
+        self.align = align
+        self._cache_maxcol = self._get_maxcol(())
+        super().__init__(self.generate_display_widget((self._cache_maxcol,)))
+
+    def _repr_words(self) -> list[str]:
+        if len(self.contents) > 1:
+            contents_string = f"({len(self.contents)} items)"
+        elif self.contents:
+            contents_string = "(1 item)"
+        else:
+            contents_string = "()"
+        return [*super()._repr_words(), contents_string]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "cell_width": self.cell_width,
+            "h_sep": self.h_sep,
+            "v_sep": self.v_sep,
+            "align": self.align,
+            "focus": self.focus_position if len(self._contents) > 1 else None,
+        }
+        return remove_defaults(attrs, GridFlow.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        yield "cells", [widget for widget, _ in self.contents]
+        yield "cell_width", self.cell_width
+        yield "h_sep", self.h_sep
+        yield "v_sep", self.v_sep
+        yield "align", self.align
+        yield "focus", self.focus_position
+
+    def __len__(self) -> int:
+        return len(self._contents)
+
+    def _invalidate(self) -> None:
+        self._cache_maxcol = None
+        super()._invalidate()
+
+    def _contents_modified(
+        self,
+        _slc: tuple[int, int, int],
+        new_items: Iterable[tuple[Widget, tuple[Literal["given", WHSettings.GIVEN], int]]],
+    ) -> None:
+        for item in new_items:
+            try:
+                _w, (t, _n) = item
+                if t != WHSettings.GIVEN:
+                    raise GridFlowError(f"added content invalid {item!r}")
+            except (TypeError, ValueError) as exc:  # noqa: PERF203
+                raise GridFlowError(f"added content invalid {item!r}").with_traceback(exc.__traceback__) from exc
+
+    @property
+    def cells(self):
+        """
+        A list of the widgets in this GridFlow
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`contents` to modify GridFlow
+            contents.
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You should use the new standard container property `contents` to modify GridFlow."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(w for w, t in self.contents)
+
+        def user_modified():
+            self.cells = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @cells.setter
+    def cells(self, widgets: Sequence[Widget]):
+        warnings.warn(
+            "only for backwards compatibility."
+            "You should use the new standard container property `contents` to modify GridFlow."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        focus_position = self.focus_position
+        self.contents = [(new, (WHSettings.GIVEN, self._cell_width)) for new in widgets]
+        if focus_position < len(widgets):
+            self.focus_position = focus_position
+
+    @property
+    def cell_width(self) -> int:
+        """
+        The width of each cell in the GridFlow. Setting this value affects
+        all cells.
+        """
+        return self._cell_width
+
+    @cell_width.setter
+    def cell_width(self, width: int) -> None:
+        focus_position = self.focus_position
+        self.contents = [(w, (WHSettings.GIVEN, width)) for (w, options) in self.contents]
+        self.focus_position = focus_position
+        self._cell_width = width
+
+    @property
+    def contents(self) -> MonitoredFocusList[tuple[Widget, tuple[Literal[WHSettings.GIVEN], int]]]:
+        """
+        The contents of this GridFlow as a list of (widget, options)
+        tuples.
+
+        options is currently a tuple in the form `('fixed', number)`.
+        number is the number of screen columns to allocate to this cell.
+        'fixed' is the only type accepted at this time.
+
+        This list may be modified like a normal list and the GridFlow
+        widget will update automatically.
+
+        .. seealso:: Create new options tuples with the :meth:`options` method.
+        """
+        return self._contents
+
+    @contents.setter
+    def contents(self, c):
+        self._contents[:] = c
+
+    def options(
+        self,
+        width_type: Literal["given", WHSettings.GIVEN] = WHSettings.GIVEN,
+        width_amount: int | None = None,
+    ) -> tuple[Literal[WHSettings.GIVEN], int]:
+        """
+        Return a new options tuple for use in a GridFlow's .contents list.
+
+        width_type -- 'given' is the only value accepted
+        width_amount -- None to use the default cell_width for this GridFlow
+        """
+        if width_type != WHSettings.GIVEN:
+            raise GridFlowError(f"invalid width_type: {width_type!r}")
+        if width_amount is None:
+            width_amount = self._cell_width
+        return (WHSettings(width_type), width_amount)
+
+    def set_focus(self, cell: Widget | int) -> None:
+        """
+        Set the cell in focus, for backwards compatibility.
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus_position` to get the focus.
+
+        :param cell: contained element to focus
+        :type cell: Widget or int
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus_position` to set the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if isinstance(cell, int):
+            try:
+                if cell < 0 or cell >= len(self.contents):
+                    raise IndexError(f"No GridFlow child widget at position {cell}")
+            except TypeError as exc:
+                raise IndexError(f"No GridFlow child widget at position {cell}").with_traceback(
+                    exc.__traceback__
+                ) from exc
+            self.contents.focus = cell
+            return
+
+        for i, (w, _options) in enumerate(self.contents):
+            if cell == w:
+                self.focus_position = i
+                return
+        raise ValueError(f"Widget not found in GridFlow contents: {cell!r}")
+
+    @property
+    def focus(self) -> Widget | None:
+        """the child widget in focus or None when GridFlow is empty"""
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    def get_focus(self):
+        """
+        Return the widget in focus, for backwards compatibility.
+
+        .. note:: only for backwards compatibility. You may also use the new
+            standard container property :attr:`focus` to get the focus.
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus` to get the focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    @property
+    def focus_cell(self):
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property"
+            "`focus` to get the focus and `focus_position` to get/set the cell in focus by index."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.focus
+
+    @focus_cell.setter
+    def focus_cell(self, cell: Widget) -> None:
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property"
+            "`focus` to get the focus and `focus_position` to get/set the cell in focus by index."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        for i, (w, _options) in enumerate(self.contents):
+            if cell == w:
+                self.focus_position = i
+                return
+        raise ValueError(f"Widget not found in GridFlow contents: {cell!r}")
+
+    @property
+    def focus_position(self) -> int | None:
+        """
+        index of child widget in focus.
+        Raises :exc:`IndexError` if read when GridFlow is empty, or when set to an invalid index.
+        """
+        if not self.contents:
+            raise IndexError("No focus_position, GridFlow is empty")
+        return self.contents.focus
+
+    @focus_position.setter
+    def focus_position(self, position: int) -> None:
+        """
+        Set the widget in focus.
+
+        position -- index of child widget to be made focus
+        """
+        try:
+            if position < 0 or position >= len(self.contents):
+                raise IndexError(f"No GridFlow child widget at position {position}")
+        except TypeError as exc:
+            raise IndexError(f"No GridFlow child widget at position {position}").with_traceback(
+                exc.__traceback__
+            ) from exc
+        self.contents.focus = position
+
+    def _get_maxcol(self, size: tuple[int] | tuple[()]) -> int:
+        if size:
+            (maxcol,) = size
+            if self and maxcol < self.cell_width:
+                warnings.warn(
+                    f"Size is smaller than cell width ({maxcol!r} < {self.cell_width!r})",
+                    GridFlowWarning,
+                    stacklevel=3,
+                )
+        elif self:
+            maxcol = len(self) * self.cell_width + (len(self) - 1) * self.h_sep
+        else:
+            maxcol = 0
+        return maxcol
+
+    def get_display_widget(self, size: tuple[int] | tuple[()]) -> Divider | Pile:
+        """
+        Arrange the cells into columns (and possibly a pile) for
+        display, input or to calculate rows, and update the display
+        widget.
+        """
+        maxcol = self._get_maxcol(size)
+
+        # use cache if possible
+        if self._cache_maxcol == maxcol:
+            return self._w
+
+        self._cache_maxcol = maxcol
+        self._w = self.generate_display_widget((maxcol,))
+
+        return self._w
+
+    def generate_display_widget(self, size: tuple[int] | tuple[()]) -> Divider | Pile:
+        """
+        Actually generate display widget (ignoring cache)
+        """
+        maxcol = self._get_maxcol(size)
+
+        divider = Divider()
+        if not self.contents:
+            return divider
+
+        if self.v_sep > 1:
+            # increase size of divider
+            divider.top = self.v_sep - 1
+
+        c = None
+        p = Pile([])
+        used_space = 0
+
+        for i, (w, (_width_type, width_amount)) in enumerate(self.contents):
+            if c is None or maxcol - used_space < width_amount:
+                # starting a new row
+                if self.v_sep:
+                    p.contents.append((divider, p.options()))
+                c = Columns([], self.h_sep)
+                column_focused = False
+                pad = Padding(c, self.align)
+                # extra attribute to reference contents position
+                pad.first_position = i
+                p.contents.append((pad, p.options()))
+
+            # Use width == maxcol in case of maxcol < width amount
+            # Columns will use empty widget in case of GIVEN width > maxcol
+            c.contents.append((w, c.options(WHSettings.GIVEN, min(width_amount, maxcol))))
+            if (i == self.focus_position) or (not column_focused and w.selectable()):
+                c.focus_position = len(c.contents) - 1
+                column_focused = True
+            if i == self.focus_position:
+                p.focus_position = len(p.contents) - 1
+            used_space = sum(x[1][1] for x in c.contents) + self.h_sep * len(c.contents)
+            pad.width = used_space - self.h_sep
+
+        if self.v_sep:
+            # remove first divider
+            del p.contents[:1]
+        else:
+            # Ensure p __selectable is updated
+            p._contents_modified()  # pylint: disable=protected-access
+
+        return p
+
+    def _set_focus_from_display_widget(self) -> None:
+        """
+        Set the focus to the item in focus in the display widget.
+        """
+        # display widget (self._w) is always built as:
+        #
+        # Pile([
+        #     Padding(
+        #         Columns([ # possibly
+        #         cell, ...])),
+        #     Divider(), # possibly
+        #     ...])
+
+        pile_focus = self._w.focus
+        if not pile_focus:
+            return
+        c = pile_focus.base_widget
+        if c.focus:
+            col_focus_position = c.focus_position
+        else:
+            col_focus_position = 0
+        # pad.first_position was set by generate_display_widget() above
+        self.focus_position = pile_focus.first_position + col_focus_position
+
+    def keypress(
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """
+        Pass keypress to display widget for handling.
+        Captures focus changes.
+        """
+        self.get_display_widget(size)
+
+        if (key := super().keypress(size, key)) is not None:
+            return key
+
+        self._set_focus_from_display_widget()
+        return None
+
+    def pack(
+        self,
+        size: tuple[int] | tuple[()] = (),  # type: ignore[override]
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        if size:
+            return super().pack(size, focus)
+        if self:
+            cols = len(self) * self.cell_width + (len(self) - 1) * self.h_sep
+        else:
+            cols = 0
+        return cols, self.rows((cols,), focus)
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        self.get_display_widget(size)
+        return super().rows(size, focus=focus)
+
+    def render(
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        focus: bool = False,
+    ):
+        self.get_display_widget(size)
+        return super().render(size, focus)
+
+    def get_cursor_coords(self, size: tuple[int] | tuple[()]) -> tuple[int, int]:
+        """Get cursor from display widget."""
+        self.get_display_widget(size)
+        return super().get_cursor_coords(size)
+
+    def move_cursor_to_coords(self, size: tuple[int] | tuple[()], col: int, row: int):
+        """Set the widget in focus based on the col + row."""
+        self.get_display_widget(size)
+        rval = super().move_cursor_to_coords(size, col, row)
+        self._set_focus_from_display_widget()
+        return rval
+
+    def mouse_event(
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> Literal[True]:
+        self.get_display_widget(size)
+        super().mouse_event(size, event, button, col, row, focus)
+        self._set_focus_from_display_widget()
+        return True  # at a minimum we adjusted our focus
+
+    def get_pref_col(self, size: tuple[int] | tuple[()]):
+        """Return pref col from display widget."""
+        self.get_display_widget(size)
+        return super().get_pref_col(size)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/line_box.py b/python/user_packages/Python313/site-packages/urwid/widget/line_box.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ea1bbcc4005879c0a17cb30476c906f7f2611b8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/line_box.py
@@ -0,0 +1,207 @@
+from __future__ import annotations
+
+import typing
+
+from .columns import Columns
+from .constants import BOX_SYMBOLS, Align, WHSettings
+from .divider import Divider
+from .pile import Pile
+from .solid_fill import SolidFill
+from .text import Text
+from .widget_decoration import WidgetDecoration, delegate_to_widget_mixin
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+    from .widget import Widget
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class LineBox(WidgetDecoration[WrappedWidget], delegate_to_widget_mixin("_wrapped_widget")):
+    Symbols = BOX_SYMBOLS
+
+    def __init__(
+        self,
+        original_widget: WrappedWidget,
+        title: str = "",
+        title_align: Literal["left", "center", "right"] | Align = Align.CENTER,
+        title_attr=None,
+        tlcorner: str = BOX_SYMBOLS.LIGHT.TOP_LEFT,
+        tline: str = BOX_SYMBOLS.LIGHT.HORIZONTAL,
+        lline: str = BOX_SYMBOLS.LIGHT.VERTICAL,
+        trcorner: str = BOX_SYMBOLS.LIGHT.TOP_RIGHT,
+        blcorner: str = BOX_SYMBOLS.LIGHT.BOTTOM_LEFT,
+        rline: str = BOX_SYMBOLS.LIGHT.VERTICAL,
+        bline: str = BOX_SYMBOLS.LIGHT.HORIZONTAL,
+        brcorner: str = BOX_SYMBOLS.LIGHT.BOTTOM_RIGHT,
+    ) -> None:
+        """
+        Draw a line around original_widget.
+
+        Use 'title' to set an initial title text with will be centered
+        on top of the box.
+
+        Use `title_attr` to apply a specific attribute to the title text.
+
+        Use `title_align` to align the title to the 'left', 'right', or 'center'.
+        The default is 'center'.
+
+        You can also override the widgets used for the lines/corners:
+            tline: top line
+            bline: bottom line
+            lline: left line
+            rline: right line
+            tlcorner: top left corner
+            trcorner: top right corner
+            blcorner: bottom left corner
+            brcorner: bottom right corner
+
+        If empty string is specified for one of the lines/corners, then no character will be output there.
+        If no top/bottom/left/right lines - whole lines will be omitted.
+        This allows for seamless use of adjoining LineBoxes.
+
+        Class attribute `Symbols` can be used as source for standard lines:
+
+        >>> print(LineBox(Text("Some text")).render(()))
+        ┌─────────┐
+        │Some text│
+        └─────────┘
+        >>> print(
+        ...     LineBox(
+        ...         Text("Some text"),
+        ...         tlcorner=LineBox.Symbols.LIGHT.TOP_LEFT_ROUNDED,
+        ...         trcorner=LineBox.Symbols.LIGHT.TOP_RIGHT_ROUNDED,
+        ...         blcorner=LineBox.Symbols.LIGHT.BOTTOM_LEFT_ROUNDED,
+        ...         brcorner=LineBox.Symbols.LIGHT.BOTTOM_RIGHT_ROUNDED,
+        ...     ).render(())
+        ... )
+        ╭─────────╮
+        │Some text│
+        ╰─────────╯
+        >>> print(
+        ...     LineBox(
+        ...         Text("Some text"),
+        ...         tline=LineBox.Symbols.HEAVY.HORIZONTAL,
+        ...         bline=LineBox.Symbols.HEAVY.HORIZONTAL,
+        ...         lline=LineBox.Symbols.HEAVY.VERTICAL,
+        ...         rline=LineBox.Symbols.HEAVY.VERTICAL,
+        ...         tlcorner=LineBox.Symbols.HEAVY.TOP_LEFT,
+        ...         trcorner=LineBox.Symbols.HEAVY.TOP_RIGHT,
+        ...         blcorner=LineBox.Symbols.HEAVY.BOTTOM_LEFT,
+        ...         brcorner=LineBox.Symbols.HEAVY.BOTTOM_RIGHT,
+        ...     ).render(())
+        ... )
+        ┏━━━━━━━━━┓
+        ┃Some text┃
+        ┗━━━━━━━━━┛
+
+        To make Table constructions, some lineboxes need to be drawn without sides
+        and T or CROSS symbols used for corners of cells.
+        """
+
+        w_lline = SolidFill(lline)
+        w_rline = SolidFill(rline)
+
+        w_tlcorner, w_tline, w_trcorner = Text(tlcorner), Divider(tline), Text(trcorner)
+        w_blcorner, w_bline, w_brcorner = Text(blcorner), Divider(bline), Text(brcorner)
+
+        if not tline and title:
+            raise ValueError("Cannot have a title when tline is empty string")
+
+        if title_attr:
+            self.title_widget = Text((title_attr, self.format_title(title)))
+        else:
+            self.title_widget = Text(self.format_title(title))
+
+        if tline:
+            if title_align not in {Align.LEFT, Align.CENTER, Align.RIGHT}:
+                raise ValueError('title_align must be one of "left", "right", or "center"')
+            if title_align == Align.LEFT:
+                tline_widgets = [(WHSettings.PACK, self.title_widget), w_tline]
+            else:
+                tline_widgets = [w_tline, (WHSettings.PACK, self.title_widget)]
+                if title_align == Align.CENTER:
+                    tline_widgets.append(w_tline)
+
+            self.tline_widget = Columns(tline_widgets)
+            top = Columns(
+                (
+                    (int(bool(tlcorner and lline)), w_tlcorner),
+                    self.tline_widget,
+                    (int(bool(trcorner and rline)), w_trcorner),
+                )
+            )
+
+        else:
+            self.tline_widget = None
+            top = None
+
+        # Note: We need to define a fixed first widget (even if it's 0 width) so that the other
+        # widgets have something to anchor onto
+        middle = Columns(
+            ((int(bool(lline)), w_lline), original_widget, (int(bool(rline)), w_rline)),
+            box_columns=[0, 2],
+            focus_column=original_widget,
+        )
+
+        if bline:
+            bottom = Columns(
+                (
+                    (int(bool(blcorner and lline)), w_blcorner),
+                    w_bline,
+                    (int(bool(brcorner and rline)), w_brcorner),
+                )
+            )
+        else:
+            bottom = None
+
+        pile_widgets = []
+        if top:
+            pile_widgets.append((WHSettings.PACK, top))
+        pile_widgets.append(middle)
+        if bottom:
+            pile_widgets.append((WHSettings.PACK, bottom))
+
+        self._wrapped_widget = Pile(pile_widgets, focus_item=middle)
+
+        super().__init__(original_widget)
+
+    @property
+    def original_widget(self) -> WrappedWidget:
+        return super().original_widget
+
+    @original_widget.setter
+    def original_widget(self, original_widget: WrappedWidget) -> None:
+        v_index = int(bool(self.tline_widget))  # we care only about top
+        h_index = 1  # constant
+        middle: Columns = typing.cast("Columns", self._wrapped_widget[v_index])
+        _old_widget, options = middle.contents[h_index]
+        middle.contents[h_index] = (original_widget, options)
+        WidgetDecoration.original_widget.fset(self, original_widget)  # pylint: disable=no-member
+
+    @property
+    def _w(self) -> Pile:
+        return self._wrapped_widget
+
+    def format_title(self, text: str) -> str:
+        if text:
+            return f" {text} "
+
+        return ""
+
+    def set_title(self, text: str) -> None:
+        if not self.tline_widget:
+            raise ValueError("Cannot set title when tline is unset")
+        self.title_widget.set_text(self.format_title(text))
+        self.tline_widget._invalidate()
+
+    @property
+    def focus(self) -> Widget | None:
+        """LineBox is partially container.
+
+        While focus position is a bit hacky
+        (formally it's not container and only position 0 available),
+        focus widget is always provided by original widget.
+        """
+        return self._original_widget.focus
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/listbox.py b/python/user_packages/Python313/site-packages/urwid/widget/listbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..deabd4b78ab3b39a713206a5edd49e3c350e9941
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/listbox.py
@@ -0,0 +1,2013 @@
+# Urwid listbox class
+#    Copyright (C) 2004-2012  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+from __future__ import annotations
+
+import operator
+import typing
+import warnings
+from collections.abc import Iterable, Sized
+from contextlib import suppress
+
+from urwid import signals
+from urwid.canvas import CanvasCombine, SolidCanvas
+
+from .constants import Sizing, VAlign, WHSettings, normalize_valign
+from .container import WidgetContainerMixin
+from .filler import calculate_top_bottom_filler
+from .monitored_list import MonitoredFocusList, MonitoredList
+from .widget import Widget, nocache_widget_render_instance
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Hashable
+
+    from typing_extensions import Literal, Self
+
+    from urwid.canvas import Canvas, CompositeCanvas
+
+__all__ = (
+    "ListBox",
+    "ListBoxError",
+    "ListWalker",
+    "ListWalkerError",
+    "SimpleFocusListWalker",
+    "SimpleListWalker",
+    "VisibleInfo",
+    "VisibleInfoFillItem",
+    "VisibleInfoMiddle",
+    "VisibleInfoTopBottom",
+)
+
+_T = typing.TypeVar("_T")
+_K = typing.TypeVar("_K")
+
+
+class ListWalkerError(Exception):
+    pass
+
+
+@typing.runtime_checkable
+class ScrollSupportingBody(typing.Protocol):
+    """Protocol for ListWalkers."""
+
+    def get_focus(self) -> tuple[Widget, _K]: ...
+
+    def set_focus(self, position: _K) -> None: ...
+
+    def get_next(self, position: _K) -> tuple[Widget, _K] | tuple[None, None]: ...
+
+    def get_prev(self, position: _K) -> tuple[Widget, _K] | tuple[None, None]: ...
+
+
+@typing.runtime_checkable
+class EstimatedSized(typing.Protocol):
+    """Widget can estimate it's size.
+
+    PEP 424 defines API for memory-efficiency.
+    For the ListBox it's a sign of the limited body length.
+    The main use-case is lazy-load, where real length calculation is expensive.
+    """
+
+    def __length_hint__(self) -> int: ...
+
+
+class ListWalker(metaclass=signals.MetaSignals):  # pylint: disable=no-member, unsubscriptable-object
+    # mixin not named as mixin
+    signals: typing.ClassVar[list[str]] = ["modified"]
+
+    def _modified(self) -> None:
+        signals.emit_signal(self, "modified")
+
+    def get_focus(self):
+        """
+        This default implementation relies on a focus attribute and a
+        __getitem__() method defined in a subclass.
+
+        Override and don't call this method if these are not defined.
+        """
+        try:
+            focus = self.focus
+            return self[focus], focus
+        except (IndexError, KeyError, TypeError):
+            return None, None
+
+    def get_next(self, position):
+        """
+        This default implementation relies on a next_position() method and a
+        __getitem__() method defined in a subclass.
+
+        Override and don't call this method if these are not defined.
+        """
+        try:
+            position = self.next_position(position)
+            return self[position], position
+        except (IndexError, KeyError):
+            return None, None
+
+    def get_prev(self, position):
+        """
+        This default implementation relies on a prev_position() method and a
+        __getitem__() method defined in a subclass.
+
+        Override and don't call this method if these are not defined.
+        """
+        try:
+            position = self.prev_position(position)
+            return self[position], position
+        except (IndexError, KeyError):
+            return None, None
+
+
+class SimpleListWalker(MonitoredList[_T], ListWalker):
+    def __init__(self, contents: Iterable[_T], wrap_around: bool = False) -> None:
+        """
+        contents -- list to copy into this object
+
+        wrap_around -- if true, jumps to beginning/end of list on move
+
+        This class inherits :class:`MonitoredList` which means
+        it can be treated as a list.
+
+        Changes made to this object (when it is treated as a list) are
+        detected automatically and will cause ListBox objects using
+        this list walker to be updated.
+        """
+        if not isinstance(contents, Iterable):
+            raise ListWalkerError(f"SimpleListWalker expecting list like object, got: {contents!r}")
+        MonitoredList.__init__(self, contents)
+        self.focus = 0
+        self.wrap_around = wrap_around
+
+    @property
+    def contents(self) -> Self:
+        """
+        Return self.
+
+        Provides compatibility with old SimpleListWalker class.
+        """
+        return self
+
+    def _modified(self) -> None:
+        if self.focus >= len(self):
+            self.focus = max(0, len(self) - 1)
+        ListWalker._modified(self)
+
+    def set_modified_callback(self, callback: Callable[[], typing.Any]) -> typing.NoReturn:
+        """
+        This function inherited from MonitoredList is not implemented in SimpleListWalker.
+
+        Use connect_signal(list_walker, "modified", ...) instead.
+        """
+        raise NotImplementedError('Use connect_signal(list_walker, "modified", ...) instead.')
+
+    def set_focus(self, position: int) -> None:
+        """Set focus position."""
+
+        if not 0 <= position < len(self):
+            raise IndexError(f"No widget at position {position}")
+
+        self.focus = position
+        self._modified()
+
+    def next_position(self, position: int) -> int:
+        """
+        Return position after start_from.
+        """
+        if len(self) - 1 <= position:
+            if self.wrap_around:
+                return 0
+            raise IndexError
+        return position + 1
+
+    def prev_position(self, position: int) -> int:
+        """
+        Return position before start_from.
+        """
+        if position <= 0:
+            if self.wrap_around:
+                return len(self) - 1
+            raise IndexError
+        return position - 1
+
+    def positions(self, reverse: bool = False) -> Iterable[int]:
+        """
+        Optional method for returning an iterable of positions.
+        """
+        if reverse:
+            return range(len(self) - 1, -1, -1)
+        return range(len(self))
+
+
+class SimpleFocusListWalker(ListWalker, MonitoredFocusList[_T]):
+    def __init__(self, contents: Iterable[_T], wrap_around: bool = False) -> None:
+        """
+        contents -- list to copy into this object
+
+        wrap_around -- if true, jumps to beginning/end of list on move
+
+        This class inherits :class:`MonitoredList` which means
+        it can be treated as a list.
+
+        Changes made to this object (when it is treated as a list) are
+        detected automatically and will cause ListBox objects using
+        this list walker to be updated.
+
+        Also, items added or removed before the widget in focus with
+        normal list methods will cause the focus to be updated
+        intelligently.
+        """
+        if not isinstance(contents, Iterable):
+            raise ListWalkerError(f"SimpleFocusListWalker expecting iterable object, got: {contents!r}")
+        MonitoredFocusList.__init__(self, contents)
+        self.wrap_around = wrap_around
+
+    def set_modified_callback(self, callback: typing.Any) -> typing.NoReturn:
+        """
+        This function inherited from MonitoredList is not
+        implemented in SimpleFocusListWalker.
+
+        Use connect_signal(list_walker, "modified", ...) instead.
+        """
+        raise NotImplementedError('Use connect_signal(list_walker, "modified", ...) instead.')
+
+    def set_focus(self, position: int) -> None:
+        """Set focus position."""
+        self.focus = position
+        self._modified()
+
+    def next_position(self, position: int) -> int:
+        """
+        Return position after start_from.
+        """
+        if len(self) - 1 <= position:
+            if self.wrap_around:
+                return 0
+            raise IndexError
+        return position + 1
+
+    def prev_position(self, position: int) -> int:
+        """
+        Return position before start_from.
+        """
+        if position <= 0:
+            if self.wrap_around:
+                return len(self) - 1
+            raise IndexError
+        return position - 1
+
+    def positions(self, reverse: bool = False) -> Iterable[int]:
+        """
+        Optional method for returning an iterable of positions.
+        """
+        if reverse:
+            return range(len(self) - 1, -1, -1)
+        return range(len(self))
+
+
+class ListBoxError(Exception):
+    pass
+
+
+class VisibleInfoMiddle(typing.NamedTuple):
+    """Named tuple for ListBox internals."""
+
+    offset: int
+    focus_widget: Widget
+    focus_pos: Hashable
+    focus_rows: int
+    cursor: tuple[int, int] | tuple[int] | None
+
+
+class VisibleInfoFillItem(typing.NamedTuple):
+    """Named tuple for ListBox internals."""
+
+    widget: Widget
+    position: Hashable
+    rows: int
+
+
+class VisibleInfoTopBottom(typing.NamedTuple):
+    """Named tuple for ListBox internals."""
+
+    trim: int
+    fill: list[VisibleInfoFillItem]
+
+    @classmethod
+    def from_raw_data(
+        cls,
+        trim: int,
+        fill: Iterable[tuple[Widget, Hashable, int]],
+    ) -> Self:
+        """Construct from not typed data.
+
+        Useful for overridden cases."""
+        return cls(trim=trim, fill=[VisibleInfoFillItem(*item) for item in fill])  # pragma: no cover
+
+
+class VisibleInfo(typing.NamedTuple):
+    middle: VisibleInfoMiddle
+    top: VisibleInfoTopBottom
+    bottom: VisibleInfoTopBottom
+
+    @classmethod
+    def from_raw_data(
+        cls,
+        middle: tuple[int, Widget, Hashable, int, tuple[int, int] | tuple[int] | None],
+        top: tuple[int, Iterable[tuple[Widget, Hashable, int]]],
+        bottom: tuple[int, Iterable[tuple[Widget, Hashable, int]]],
+    ) -> Self:
+        """Construct from not typed data.
+
+        Useful for overridden cases.
+        """
+        return cls(  # pragma: no cover
+            middle=VisibleInfoMiddle(*middle),
+            top=VisibleInfoTopBottom.from_raw_data(*top),
+            bottom=VisibleInfoTopBottom.from_raw_data(*bottom),
+        )
+
+
+class ListBox(Widget, WidgetContainerMixin):
+    """
+    Vertically stacked list of widgets
+    """
+
+    _selectable = True
+    _sizing = frozenset([Sizing.BOX])
+
+    def __init__(self, body: ListWalker | Iterable[Widget]) -> None:
+        """
+        :param body: a ListWalker subclass such as :class:`SimpleFocusListWalker`
+            that contains widgets to be displayed inside the list box
+        :type body: ListWalker
+        """
+        super().__init__()
+        if getattr(body, "get_focus", None):
+            self._body: ListWalker = body
+        else:
+            self._body = SimpleListWalker(body)
+
+        self.body = self._body  # Initialization hack
+
+        # offset_rows is the number of rows between the top of the view
+        # and the top of the focused item
+        self.offset_rows = 0
+        # inset_fraction is used when the focused widget is off the
+        # top of the view.  it is the fraction of the widget cut off
+        # at the top.  (numerator, denominator)
+        self.inset_fraction = (0, 1)
+
+        # pref_col is the preferred column for the cursor when moving
+        # between widgets that use the cursor (edit boxes etc.)
+        self.pref_col = "left"
+
+        # variable for delayed focus change used by set_focus
+        self.set_focus_pending = "first selectable"
+
+        # variable for delayed valign change used by set_focus_valign
+        self.set_focus_valign_pending = None
+
+        # used for scrollable protocol
+        self._rows_max_cached = 0
+        self._rendered_size = 0, 0
+
+    @property
+    def body(self) -> ListWalker:
+        """
+        a ListWalker subclass such as :class:`SimpleFocusListWalker` that contains
+        widgets to be displayed inside the list box
+        """
+        return self._body
+
+    @body.setter
+    def body(self, body: Iterable[Widget] | ListWalker) -> None:
+        with suppress(AttributeError):
+            signals.disconnect_signal(self._body, "modified", self._invalidate)
+            # _body may be not yet assigned
+
+        if getattr(body, "get_focus", None):
+            self._body = body
+        else:
+            self._body = SimpleListWalker(body)
+        try:
+            signals.connect_signal(self._body, "modified", self._invalidate)
+        except NameError:
+            # our list walker has no modified signal so we must not
+            # cache our canvases because we don't know when our
+            # content has changed
+            self.render = nocache_widget_render_instance(self)
+        self._invalidate()
+
+    @property
+    def __len__(self) -> Callable[[], int]:
+        if isinstance(self._body, Sized):
+            return self._body.__len__
+        raise AttributeError(f"{self._body.__class__.__name__} is not Sized")
+
+    @property
+    def __length_hint__(self) -> Callable[[], int]:  # pylint: disable=invalid-length-hint-returned
+        if isinstance(self._body, (Sized, EstimatedSized)):
+            return lambda: operator.length_hint(self._body)
+        raise AttributeError(f'{self._body.__class__.__name__} is not Sized and do not implement "__length_hint__"')
+
+    def calculate_visible(
+        self,
+        size: tuple[int, int],
+        focus: bool = False,
+    ) -> VisibleInfo | tuple[None, None, None]:
+        """
+        Returns the widgets that would be displayed in
+        the ListBox given the current *size* and *focus*.
+
+        see :meth:`Widget.render` for parameter details
+
+        :returns: (*middle*, *top*, *bottom*) or (``None``, ``None``, ``None``)
+
+        *middle*
+            (*row offset*(when +ve) or *inset*(when -ve),
+            *focus widget*, *focus position*, *focus rows*,
+            *cursor coords* or ``None``)
+        *top*
+            (*# lines to trim off top*,
+            list of (*widget*, *position*, *rows*) tuples above focus in order from bottom to top)
+        *bottom*
+            (*# lines to trim off bottom*,
+            list of (*widget*, *position*, *rows*) tuples below focus in order from top to bottom)
+        """
+        (maxcol, maxrow) = size
+
+        # 0. set the focus if a change is pending
+        if self.set_focus_pending or self.set_focus_valign_pending:
+            self._set_focus_complete((maxcol, maxrow), focus)
+
+        # 1. start with the focus widget
+        focus_widget, focus_pos = self._body.get_focus()
+        if focus_widget is None:  # list box is empty?
+            return None, None, None
+        top_pos = focus_pos
+
+        offset_rows, inset_rows = self.get_focus_offset_inset((maxcol, maxrow))
+        #    force at least one line of focus to be visible
+        if maxrow and offset_rows >= maxrow:
+            offset_rows = maxrow - 1
+
+        #    adjust position so cursor remains visible
+        cursor = None
+        if maxrow and focus_widget.selectable() and focus and hasattr(focus_widget, "get_cursor_coords"):
+            cursor = focus_widget.get_cursor_coords((maxcol,))
+
+        if cursor is not None:
+            _cx, cy = cursor
+            effective_cy = cy + offset_rows - inset_rows
+
+            if effective_cy < 0:  # cursor above top?
+                inset_rows = cy
+            elif effective_cy >= maxrow:  # cursor below bottom?
+                offset_rows = maxrow - cy - 1
+                if offset_rows < 0:  # need to trim the top
+                    inset_rows, offset_rows = -offset_rows, 0
+
+        #    set trim_top by focus trimmimg
+        trim_top = inset_rows
+        focus_rows = focus_widget.rows((maxcol,), True)
+
+        # 2. collect the widgets above the focus
+        pos = focus_pos
+        fill_lines = offset_rows
+        fill_above = []
+        top_pos = pos
+        while fill_lines > 0:
+            prev, pos = self._body.get_prev(pos)
+            if prev is None:  # run out of widgets above?
+                offset_rows -= fill_lines
+                break
+            top_pos = pos
+
+            p_rows = prev.rows((maxcol,))
+            if p_rows:  # filter out 0-height widgets
+                fill_above.append(VisibleInfoFillItem(prev, pos, p_rows))
+            if p_rows > fill_lines:  # crosses top edge?
+                trim_top = p_rows - fill_lines
+                break
+            fill_lines -= p_rows
+
+        trim_bottom = max(focus_rows + offset_rows - inset_rows - maxrow, 0)
+
+        # 3. collect the widgets below the focus
+        pos = focus_pos
+        fill_lines = maxrow - focus_rows - offset_rows + inset_rows
+        fill_below = []
+        while fill_lines > 0:
+            next_pos, pos = self._body.get_next(pos)
+            if next_pos is None:  # run out of widgets below?
+                break
+
+            n_rows = next_pos.rows((maxcol,))
+            if n_rows:  # filter out 0-height widgets
+                fill_below.append(VisibleInfoFillItem(next_pos, pos, n_rows))
+            if n_rows > fill_lines:  # crosses bottom edge?
+                trim_bottom = n_rows - fill_lines
+                fill_lines -= n_rows
+                break
+            fill_lines -= n_rows
+
+        # 4. fill from top again if necessary & possible
+        fill_lines = max(0, fill_lines)
+
+        if fill_lines > 0 and trim_top > 0:
+            if fill_lines <= trim_top:
+                trim_top -= fill_lines
+                offset_rows += fill_lines
+                fill_lines = 0
+            else:
+                fill_lines -= trim_top
+                offset_rows += trim_top
+                trim_top = 0
+        pos = top_pos
+        while fill_lines > 0:
+            prev, pos = self._body.get_prev(pos)
+            if prev is None:
+                break
+
+            p_rows = prev.rows((maxcol,))
+            fill_above.append(VisibleInfoFillItem(prev, pos, p_rows))
+            if p_rows > fill_lines:  # more than required
+                trim_top = p_rows - fill_lines
+                offset_rows += fill_lines
+                break
+            fill_lines -= p_rows
+            offset_rows += p_rows
+
+        # 5. return the interesting bits
+        return VisibleInfo(
+            VisibleInfoMiddle(offset_rows - inset_rows, focus_widget, focus_pos, focus_rows, cursor),
+            VisibleInfoTopBottom(trim_top, fill_above),
+            VisibleInfoTopBottom(trim_bottom, fill_below),
+        )
+
+    def _check_support_scrolling(self) -> None:
+        from .treetools import TreeWalker
+
+        if not isinstance(self._body, ScrollSupportingBody):
+            raise ListBoxError(f"{self} body do not implement methods required for scrolling protocol")
+
+        if not isinstance(self._body, (Sized, EstimatedSized, TreeWalker)):
+            raise ListBoxError(
+                f"{self} body is not a Sized, can not estimate it's size and not a TreeWalker."
+                f"Scroll is not allowed due to risk of infinite cycle of widgets load."
+            )
+
+        if getattr(self._body, "wrap_around", False):
+            raise ListBoxError("Body is wrapped around. Scroll position calculation is undefined.")
+
+    def get_scrollpos(self, size: tuple[int, int] | None = None, focus: bool = False) -> int:
+        """Current scrolling position."""
+        self._check_support_scrolling()
+
+        if not self._body:
+            return 0
+
+        if size is not None:
+            self._rendered_size = size
+
+        mid, top, _bottom = self.calculate_visible(self._rendered_size, focus)
+
+        start_row = top.trim
+        maxcol = self._rendered_size[0]
+
+        if top.fill:
+            pos = top.fill[-1].position
+        else:
+            pos = mid.focus_pos
+
+        prev, pos = self._body.get_prev(pos)
+        while prev is not None:
+            start_row += prev.rows((maxcol,))
+            prev, pos = self._body.get_prev(pos)
+
+        return start_row
+
+    def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int:
+        """Scrollable protocol for sized iterable and not wrapped around contents."""
+        self._check_support_scrolling()
+
+        if size is not None:
+            self._rendered_size = size
+
+        if size or not self._rows_max_cached:
+            cols = self._rendered_size[0]
+            rows = 0
+
+            focused_w, idx = self.body.get_focus()
+            if focused_w:
+                rows += focused_w.rows((cols,), focus)
+
+                prev, pos = self._body.get_prev(idx)
+                while prev is not None:
+                    rows += prev.rows((cols,), False)
+                    prev, pos = self._body.get_prev(pos)
+
+                next_, pos = self.body.get_next(idx)
+                while next_ is not None:
+                    rows += next_.rows((cols,), True)
+                    next_, pos = self._body.get_next(pos)
+
+            self._rows_max_cached = rows
+
+        return self._rows_max_cached
+
+    def require_relative_scroll(self, size: tuple[int, int], focus: bool = False) -> bool:
+        """Widget require relative scroll due to performance limitations of real lines count calculation."""
+        return isinstance(self._body, (Sized, EstimatedSized)) and (size[1] * 3 < operator.length_hint(self.body))
+
+    def get_first_visible_pos(self, size: tuple[int, int], focus: bool = False) -> int:
+        self._check_support_scrolling()
+
+        if not self._body:
+            return 0
+
+        _mid, top, _bottom = self.calculate_visible(size, focus)
+        if top.fill:
+            first_pos = top.fill[-1].position
+        else:
+            first_pos = self.focus_position
+
+        over = 0
+        _widget, first_pos = self.body.get_prev(first_pos)
+        while first_pos is not None:
+            over += 1
+            _widget, first_pos = self.body.get_prev(first_pos)
+
+        return over
+
+    def get_visible_amount(self, size: tuple[int, int], focus: bool = False) -> int:
+        self._check_support_scrolling()
+
+        if not self._body:
+            return 1
+
+        _mid, top, bottom = self.calculate_visible(size, focus)
+        return 1 + len(top.fill) + len(bottom.fill)
+
+    def render(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas | SolidCanvas:
+        """
+        Render ListBox and return canvas.
+
+        see :meth:`Widget.render` for details
+        """
+        (maxcol, maxrow) = size
+
+        self._rendered_size = size
+
+        middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus)
+        if middle is None:
+            return SolidCanvas(" ", maxcol, maxrow)
+
+        _ignore, focus_widget, focus_pos, focus_rows, cursor = middle  # pylint: disable=unpacking-non-sequence
+        trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+        trim_bottom, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        combinelist: list[tuple[Canvas, int, bool]] = []
+        rows = 0
+        fill_above.reverse()  # fill_above is in bottom-up order
+        for widget, w_pos, w_rows in fill_above:
+            canvas = widget.render((maxcol,))
+            if w_rows != canvas.rows():
+                raise ListBoxError(
+                    f"Widget {widget!r} at position {w_pos!r} "
+                    f"within listbox calculated {w_rows:d} rows "
+                    f"but rendered {canvas.rows():d}!"
+                )
+            rows += w_rows
+            combinelist.append((canvas, w_pos, False))
+
+        focus_canvas = focus_widget.render((maxcol,), focus=focus)
+
+        if focus_canvas.rows() != focus_rows:
+            raise ListBoxError(
+                f"Focus Widget {focus_widget!r} at position {focus_pos!r} "
+                f"within listbox calculated {focus_rows:d} rows "
+                f"but rendered {focus_canvas.rows():d}!"
+            )
+        c_cursor = focus_canvas.cursor
+        if cursor is not None and cursor != c_cursor:
+            raise ListBoxError(
+                f"Focus Widget {focus_widget!r} at position {focus_pos!r} "
+                f"within listbox calculated cursor coords {cursor!r} "
+                f"but rendered cursor coords {c_cursor!r}!"
+            )
+
+        rows += focus_rows
+        combinelist.append((focus_canvas, focus_pos, True))
+
+        for widget, w_pos, w_rows in fill_below:
+            canvas = widget.render((maxcol,))
+            if w_rows != canvas.rows():
+                raise ListBoxError(
+                    f"Widget {widget!r} at position {w_pos!r} "
+                    f"within listbox calculated {w_rows:d} "
+                    f"rows but rendered {canvas.rows():d}!"
+                )
+            rows += w_rows
+            combinelist.append((canvas, w_pos, False))
+
+        final_canvas = CanvasCombine(combinelist)
+
+        if trim_top:
+            final_canvas.trim(trim_top)
+            rows -= trim_top
+        if trim_bottom:
+            final_canvas.trim_end(trim_bottom)
+            rows -= trim_bottom
+
+        if rows > maxrow:
+            raise ListBoxError(
+                f"Listbox contents too long!\nRender top={top!r}, middle={middle!r}, bottom={bottom!r}\n"
+            )
+
+        if rows < maxrow:
+            if trim_bottom != 0:
+                raise ListBoxError(
+                    f"Listbox contents too short!\n"
+                    f"Render top={top!r}, middle={middle!r}, bottom={bottom!r}\n"
+                    f"Trim bottom={trim_bottom!r}"
+                )
+
+            bottom_pos = focus_pos
+            if fill_below:
+                bottom_pos = fill_below[-1][1]
+
+            rendered_positions = frozenset(idx for _, idx, _ in combinelist)
+            widget, next_pos = self._body.get_next(bottom_pos)
+            while all(
+                (
+                    widget is not None,
+                    next_pos is not None,
+                    next_pos not in rendered_positions,
+                )
+            ):
+                if widget.rows((maxcol,), False):
+                    raise ListBoxError(
+                        f"Listbox contents too short!\n"
+                        f"Render top={top!r}, middle={middle!r}, bottom={bottom!r}\n"
+                        f"Not rendered not empty widgets available (first is {widget!r} with position {next_pos!r})"
+                    )
+
+                widget, next_next_pos = self._body.get_next(next_pos)
+                if next_pos == next_next_pos:
+                    raise ListBoxError(
+                        f"Next position after {next_pos!r} is invalid (points to itself)\n"
+                        f"Looks like bug with {self._body!r}"
+                    )
+                next_pos = next_next_pos
+
+            final_canvas.pad_trim_top_bottom(0, maxrow - rows)
+
+        return final_canvas
+
+    def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None:
+        """
+        See :meth:`Widget.get_cursor_coords` for details
+        """
+        (maxcol, maxrow) = size
+
+        middle, _top, _bottom = self.calculate_visible((maxcol, maxrow), True)
+        if middle is None:
+            return None
+
+        offset_inset, _ignore1, _ignore2, _ignore3, cursor = middle  # pylint: disable=unpacking-non-sequence
+        if not cursor:
+            return None
+
+        x, y = cursor
+        y += offset_inset
+        if y < 0 or y >= maxrow:
+            return None
+        return (x, y)
+
+    def set_focus_valign(
+        self,
+        valign: Literal["top", "middle", "bottom"] | VAlign | tuple[Literal["relative", WHSettings.RELATIVE], int],
+    ):
+        """Set the focus widget's display offset and inset.
+
+        :param valign: one of: 'top', 'middle', 'bottom' ('relative', percentage 0=top 100=bottom)
+        """
+        vt, va = normalize_valign(valign, ListBoxError)
+        self.set_focus_valign_pending = vt, va
+
+    def set_focus(self, position, coming_from: Literal["above", "below"] | None = None) -> None:
+        """
+        Set the focus position and try to keep the old focus in view.
+
+        :param position: a position compatible with :meth:`self._body.set_focus`
+        :param coming_from: set to 'above' or 'below' if you know that
+                            old position is above or below the new position.
+        :type coming_from: str
+        """
+        if coming_from not in {"above", "below", None}:
+            raise ListBoxError(f"coming_from value invalid: {coming_from!r}")
+        focus_widget, focus_pos = self._body.get_focus()
+        if focus_widget is None:
+            raise IndexError("Can't set focus, ListBox is empty")
+
+        self.set_focus_pending = coming_from, focus_widget, focus_pos
+        self._body.set_focus(position)
+
+    def get_focus(self):
+        """
+        Return a `(focus widget, focus position)` tuple, for backwards
+        compatibility. You may also use the new standard container
+        properties :attr:`focus` and :attr:`focus_position` to read these values.
+        """
+        warnings.warn(
+            "only for backwards compatibility."
+            "You may also use the new standard container property `focus` to get the focus "
+            "and property `focus_position` to read these values."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self._body.get_focus()
+
+    @property
+    def focus(self) -> Widget | None:
+        """
+        the child widget in focus or None when ListBox is empty.
+
+        Return the widget in focus according to our :obj:`list walker `.
+        """
+        return self._body.get_focus()[0]
+
+    def _get_focus_position(self):
+        """
+        Return the list walker position of the widget in focus. The type
+        of value returned depends on the :obj:`list walker `.
+
+        """
+        w, pos = self._body.get_focus()
+        if w is None:
+            raise IndexError("No focus_position, ListBox is empty")
+        return pos
+
+    focus_position = property(
+        _get_focus_position,
+        set_focus,
+        doc="""
+        the position of child widget in focus. The valid values for this
+        position depend on the list walker in use.
+        :exc:`IndexError` will be raised by reading this property when the
+        ListBox is empty or setting this property to an invalid position.
+        """,
+    )
+
+    def _contents(self):
+        # noinspection PyMethodParameters
+        class ListBoxContents:
+            # pylint: disable=no-self-argument
+
+            __getitem__ = self._contents__getitem__
+
+            __len__ = self.__len__
+
+            def __repr__(inner_self) -> str:
+                return f"<{inner_self.__class__.__name__} for {self!r} at 0x{id(inner_self):X}>"
+
+            def __call__(inner_self) -> Self:
+                warnings.warn(
+                    "ListBox.contents is a property, not a method",
+                    DeprecationWarning,
+                    stacklevel=3,
+                )
+                return inner_self
+
+        return ListBoxContents()
+
+    def _contents__getitem__(self, key):
+        # try list walker protocol v2 first
+        if hasattr(self._body, "__getitem__"):
+            try:
+                return (self._body[key], None)
+            except (IndexError, KeyError) as exc:
+                raise KeyError(f"ListBox.contents key not found: {key!r}").with_traceback(exc.__traceback__) from exc
+        # fall back to v1
+        _w, old_focus = self._body.get_focus()
+
+        try:
+            self._body.set_focus(key)
+            return self._body.get_focus()[0]
+        except (IndexError, KeyError) as exc:
+            raise KeyError(f"ListBox.contents key not found: {key!r}").with_traceback(exc.__traceback__) from exc
+        finally:
+            self._body.set_focus(old_focus)
+
+    @property
+    def contents(self):
+        """
+        An object that allows reading widgets from the ListBox's list
+        walker as a `(widget, options)` tuple. `None` is currently the only
+        value for options.
+
+        .. warning::
+
+            This object may not be used to set or iterate over contents.
+
+            You must use the list walker stored as
+            :attr:`.body` to perform manipulation and iteration, if supported.
+        """
+        return self._contents()
+
+    def options(self):
+        """
+        There are currently no options for ListBox contents.
+
+        Return None as a placeholder for future options.
+        """
+
+    def _set_focus_valign_complete(self, size: tuple[int, int], focus: bool) -> None:
+        """Finish setting the offset and inset now that we have have a maxcol & maxrow."""
+        (maxcol, maxrow) = size
+        vt, va = self.set_focus_valign_pending
+        self.set_focus_valign_pending = None
+        self.set_focus_pending = None
+
+        focus_widget, _focus_pos = self._body.get_focus()
+        if focus_widget is None:
+            return
+
+        rows = focus_widget.rows((maxcol,), focus)
+        rtop, _rbot = calculate_top_bottom_filler(
+            maxrow,
+            vt,
+            va,
+            WHSettings.GIVEN,
+            rows,
+            None,
+            0,
+            0,
+        )
+
+        self.shift_focus((maxcol, maxrow), rtop)
+
+    def _set_focus_first_selectable(self, size: tuple[int, int], focus: bool) -> None:
+        """Choose the first visible, selectable widget below the current focus as the focus widget."""
+        (maxcol, maxrow) = size
+        self.set_focus_valign_pending = None
+        self.set_focus_pending = None
+        middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus)
+        if middle is None:
+            return
+
+        row_offset, focus_widget, _focus_pos, focus_rows, _cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_top, _fill_above = top  # pylint: disable=unpacking-non-sequence
+        trim_bottom, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        if focus_widget.selectable():
+            return
+
+        if trim_bottom:
+            fill_below = fill_below[:-1]
+        new_row_offset = row_offset + focus_rows
+        for widget, pos, rows in fill_below:
+            if widget.selectable():
+                self._body.set_focus(pos)
+                self.shift_focus((maxcol, maxrow), new_row_offset)
+                return
+            new_row_offset += rows
+
+    def _set_focus_complete(self, size: tuple[int, int], focus: bool) -> None:
+        """Finish setting the position now that we have maxcol & maxrow."""
+        (maxcol, maxrow) = size
+        self._invalidate()
+        if self.set_focus_pending == "first selectable":
+            return self._set_focus_first_selectable((maxcol, maxrow), focus)
+        if self.set_focus_valign_pending is not None:
+            return self._set_focus_valign_complete((maxcol, maxrow), focus)
+        coming_from, _focus_widget, focus_pos = self.set_focus_pending
+        self.set_focus_pending = None
+
+        # new position
+        _new_focus_widget, position = self._body.get_focus()
+        if focus_pos == position:
+            # do nothing
+            return None
+
+        # restore old focus temporarily
+        self._body.set_focus(focus_pos)
+
+        middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus)
+        if middle is None:
+            return None
+
+        focus_offset, _focus_widget, focus_pos, focus_rows, _cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+        _trim_bottom, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        offset = focus_offset
+        for _widget, pos, rows in fill_above:
+            offset -= rows
+            if pos == position:
+                self.change_focus((maxcol, maxrow), pos, offset, "below")
+                return None
+
+        offset = focus_offset + focus_rows
+        for _widget, pos, rows in fill_below:
+            if pos == position:
+                self.change_focus((maxcol, maxrow), pos, offset, "above")
+                return None
+            offset += rows
+
+        # failed to find widget among visible widgets
+        self._body.set_focus(position)
+        widget, position = self._body.get_focus()
+        rows = widget.rows((maxcol,), focus)
+
+        if coming_from == "below":
+            offset = 0
+        elif coming_from == "above":
+            offset = maxrow - rows
+        else:
+            offset = (maxrow - rows) // 2
+        self.shift_focus((maxcol, maxrow), offset)
+        return None
+
+    def shift_focus(self, size: tuple[int, int], offset_inset: int) -> None:
+        """
+        Move the location of the current focus relative to the top.
+        This is used internally by methods that know the widget's *size*.
+
+        See also :meth:`.set_focus_valign`.
+
+        :param size: see :meth:`Widget.render` for details
+        :param offset_inset: either the number of rows between the
+            top of the listbox and the start of the focus widget (+ve
+            value) or the number of lines of the focus widget hidden off
+            the top edge of the listbox (-ve value) or ``0`` if the top edge
+            of the focus widget is aligned with the top edge of the
+            listbox.
+        :type offset_inset: int
+        """
+        (maxcol, maxrow) = size
+
+        if offset_inset >= 0:
+            if offset_inset >= maxrow:
+                raise ListBoxError(f"Invalid offset_inset: {offset_inset!r}, only {maxrow!r} rows in list box")
+            self.offset_rows = offset_inset
+            self.inset_fraction = (0, 1)
+        else:
+            target, _ignore = self._body.get_focus()
+            tgt_rows = target.rows((maxcol,), True)
+            if offset_inset + tgt_rows <= 0:
+                raise ListBoxError(f"Invalid offset_inset: {offset_inset!r}, only {tgt_rows!r} rows in target!")
+            self.offset_rows = 0
+            self.inset_fraction = (-offset_inset, tgt_rows)
+        self._invalidate()
+
+    def update_pref_col_from_focus(self, size: tuple[int, int]) -> None:
+        """Update self.pref_col from the focus widget."""
+        # TODO: should this not be private?
+        (maxcol, _maxrow) = size
+
+        widget, _old_pos = self._body.get_focus()
+        if widget is None:
+            return
+
+        pref_col = None
+        if hasattr(widget, "get_pref_col"):
+            pref_col = widget.get_pref_col((maxcol,))
+        if pref_col is None and hasattr(widget, "get_cursor_coords"):
+            coords = widget.get_cursor_coords((maxcol,))
+            if isinstance(coords, tuple):
+                pref_col, _y = coords
+        if pref_col is not None:
+            self.pref_col = pref_col
+
+    def change_focus(
+        self,
+        size: tuple[int, int],
+        position,
+        offset_inset: int = 0,
+        coming_from: Literal["above", "below"] | None = None,
+        cursor_coords: tuple[int, int] | None = None,
+        snap_rows: int | None = None,
+    ) -> None:
+        """
+        Change the current focus widget.
+        This is used internally by methods that know the widget's *size*.
+
+        See also :meth:`.set_focus`.
+
+        :param size: see :meth:`Widget.render` for details
+        :param position: a position compatible with :meth:`self._body.set_focus`
+        :param offset_inset: either the number of rows between the
+            top of the listbox and the start of the focus widget (+ve
+            value) or the number of lines of the focus widget hidden off
+            the top edge of the listbox (-ve value) or 0 if the top edge
+            of the focus widget is aligned with the top edge of the
+            listbox (default if unspecified)
+        :type offset_inset: int
+        :param coming_from: either 'above', 'below' or unspecified `None`
+        :type coming_from: str
+        :param cursor_coords: (x, y) tuple indicating the desired
+            column and row for the cursor, a (x,) tuple indicating only
+            the column for the cursor, or unspecified
+        :type cursor_coords: (int, int)
+        :param snap_rows: the maximum number of extra rows to scroll
+            when trying to "snap" a selectable focus into the view
+        :type snap_rows: int
+        """
+        (maxcol, maxrow) = size
+
+        # update pref_col before change
+        if cursor_coords:
+            self.pref_col = cursor_coords[0]
+        else:
+            self.update_pref_col_from_focus((maxcol, maxrow))
+
+        self._invalidate()
+        self._body.set_focus(position)
+        target, _ignore = self._body.get_focus()
+        tgt_rows = target.rows((maxcol,), True)
+        if snap_rows is None:
+            snap_rows = maxrow - 1
+
+        # "snap" to selectable widgets
+        align_top = 0
+        align_bottom = maxrow - tgt_rows
+
+        if coming_from == "above" and target.selectable() and offset_inset > align_bottom:
+            if snap_rows >= offset_inset - align_bottom:
+                offset_inset = align_bottom
+            elif snap_rows >= offset_inset - align_top:
+                offset_inset = align_top
+            else:
+                offset_inset -= snap_rows
+
+        if coming_from == "below" and target.selectable() and offset_inset < align_top:
+            if snap_rows >= align_top - offset_inset:
+                offset_inset = align_top
+            elif snap_rows >= align_bottom - offset_inset:
+                offset_inset = align_bottom
+            else:
+                offset_inset += snap_rows
+
+        # convert offset_inset to offset_rows or inset_fraction
+        if offset_inset >= 0:
+            self.offset_rows = offset_inset
+            self.inset_fraction = (0, 1)
+        else:
+            if offset_inset + tgt_rows <= 0:
+                raise ListBoxError(f"Invalid offset_inset: {offset_inset}, only {tgt_rows} rows in target!")
+            self.offset_rows = 0
+            self.inset_fraction = (-offset_inset, tgt_rows)
+
+        if cursor_coords is None:
+            if coming_from is None:
+                return  # must either know row or coming_from
+            cursor_coords = (self.pref_col,)
+
+        if not hasattr(target, "move_cursor_to_coords"):
+            return
+
+        attempt_rows = []
+
+        if len(cursor_coords) == 1:
+            # only column (not row) specified
+            # start from closest edge and move inwards
+            (pref_col,) = cursor_coords
+            if coming_from == "above":
+                attempt_rows = range(tgt_rows)
+            else:
+                if coming_from != "below":
+                    raise ValueError("must specify coming_from ('above' or 'below') if cursor row is not specified")
+                attempt_rows = range(tgt_rows, -1, -1)
+        else:
+            # both column and row specified
+            # start from preferred row and move back to closest edge
+            (pref_col, pref_row) = cursor_coords
+            if pref_row < 0 or pref_row >= tgt_rows:
+                raise ListBoxError(
+                    f"cursor_coords row outside valid range for target. pref_row:{pref_row!r} target_rows:{tgt_rows!r}"
+                )
+
+            if coming_from == "above":
+                attempt_rows = range(pref_row, -1, -1)
+            elif coming_from == "below":
+                attempt_rows = range(pref_row, tgt_rows)
+            else:
+                attempt_rows = [pref_row]
+
+        for row in attempt_rows:
+            if target.move_cursor_to_coords((maxcol,), pref_col, row):
+                break
+
+    def get_focus_offset_inset(self, size: tuple[int, int]) -> tuple[int, int]:
+        """Return (offset rows, inset rows) for focus widget."""
+        (maxcol, _maxrow) = size
+        focus_widget, _pos = self._body.get_focus()
+        focus_rows = focus_widget.rows((maxcol,), True)
+        offset_rows = self.offset_rows
+        inset_rows = 0
+        if offset_rows == 0:
+            inum, iden = self.inset_fraction
+            if inum < 0 or iden < 0 or inum >= iden:
+                raise ListBoxError(f"Invalid inset_fraction: {self.inset_fraction!r}")
+            inset_rows = focus_rows * inum // iden
+            if inset_rows and inset_rows >= focus_rows:
+                raise ListBoxError("urwid inset_fraction error (please report)")
+        return offset_rows, inset_rows
+
+    def make_cursor_visible(self, size: tuple[int, int]) -> None:
+        """Shift the focus widget so that its cursor is visible."""
+        (maxcol, maxrow) = size
+
+        focus_widget, _pos = self._body.get_focus()
+        if focus_widget is None:
+            return
+        if not focus_widget.selectable():
+            return
+        if not hasattr(focus_widget, "get_cursor_coords"):
+            return
+        cursor = focus_widget.get_cursor_coords((maxcol,))
+        if cursor is None:
+            return
+        _cx, cy = cursor
+        offset_rows, inset_rows = self.get_focus_offset_inset((maxcol, maxrow))
+
+        if cy < inset_rows:
+            self.shift_focus((maxcol, maxrow), -(cy))
+            return
+
+        if offset_rows - inset_rows + cy >= maxrow:
+            self.shift_focus((maxcol, maxrow), maxrow - cy - 1)
+            return
+
+    def keypress(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        """Move selection through the list elements scrolling when
+        necessary. Keystrokes are first passed to widget in focus
+        in case that widget can handle them.
+
+        Keystrokes handled by this widget are:
+         'up'        up one line (or widget)
+         'down'      down one line (or widget)
+         'page up'   move cursor up one listbox length (or widget)
+         'page down' move cursor down one listbox length (or widget)
+        """
+        from urwid.command_map import Command
+
+        (maxcol, maxrow) = size
+
+        if self.set_focus_pending or self.set_focus_valign_pending:
+            self._set_focus_complete((maxcol, maxrow), focus=True)
+
+        focus_widget, _pos = self._body.get_focus()
+        if focus_widget is None:  # empty listbox, can't do anything
+            return key
+
+        if focus_widget.selectable():
+            key = focus_widget.keypress((maxcol,), key)
+            if key is None:
+                self.make_cursor_visible((maxcol, maxrow))
+                return None
+
+        def actual_key(unhandled) -> str | None:
+            if unhandled:
+                return key
+            return None
+
+        # pass off the heavy lifting
+        if self._command_map[key] == Command.UP:
+            return actual_key(self._keypress_up((maxcol, maxrow)))
+
+        if self._command_map[key] == Command.DOWN:
+            return actual_key(self._keypress_down((maxcol, maxrow)))
+
+        if self._command_map[key] == Command.PAGE_UP:
+            return actual_key(self._keypress_page_up((maxcol, maxrow)))
+
+        if self._command_map[key] == Command.PAGE_DOWN:
+            return actual_key(self._keypress_page_down((maxcol, maxrow)))
+
+        if self._command_map[key] == Command.MAX_LEFT:
+            return actual_key(self._keypress_max_left((maxcol, maxrow)))
+
+        if self._command_map[key] == Command.MAX_RIGHT:
+            return actual_key(self._keypress_max_right((maxcol, maxrow)))
+
+        return key
+
+    def _keypress_max_left(self, size: tuple[int, int]) -> None:
+        self.focus_position = next(iter(self.body.positions()))
+        self.set_focus_valign(VAlign.TOP)
+
+    def _keypress_max_right(self, size: tuple[int, int]) -> None:
+        self.focus_position = next(iter(self.body.positions(reverse=True)))
+        self.set_focus_valign(VAlign.BOTTOM)
+
+    def _keypress_up(self, size: tuple[int, int]) -> bool | None:
+        (maxcol, maxrow) = size
+
+        middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True)
+        if middle is None:
+            return True
+
+        focus_row_offset, focus_widget, focus_pos, _ignore, cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+
+        row_offset = focus_row_offset
+
+        # look for selectable widget above
+        pos = focus_pos
+        widget = None
+        for widget, pos, rows in fill_above:
+            row_offset -= rows
+            if rows and widget.selectable():
+                # this one will do
+                self.change_focus((maxcol, maxrow), pos, row_offset, "below")
+                return None
+
+        # at this point we must scroll
+        row_offset += 1
+        self._invalidate()
+
+        while row_offset > 0:
+            # need to scroll in another candidate widget
+            widget, pos = self._body.get_prev(pos)
+            if widget is None:
+                # cannot scroll any further
+                return True  # keypress not handled
+            rows = widget.rows((maxcol,), True)
+            row_offset -= rows
+            if rows and widget.selectable():
+                # this one will do
+                self.change_focus((maxcol, maxrow), pos, row_offset, "below")
+                return None
+
+        if not focus_widget.selectable() or focus_row_offset + 1 >= maxrow:
+            # just take top one if focus is not selectable
+            # or if focus has moved out of view
+            if widget is None:
+                self.shift_focus((maxcol, maxrow), row_offset)
+                return None
+            self.change_focus((maxcol, maxrow), pos, row_offset, "below")
+            return None
+
+        # check if cursor will stop scroll from taking effect
+        if cursor is not None:
+            _x, y = cursor
+            if y + focus_row_offset + 1 >= maxrow:
+                # cursor position is a problem,
+                # choose another focus
+                if widget is None:
+                    # try harder to get prev widget
+                    widget, pos = self._body.get_prev(pos)
+                    if widget is None:
+                        return None  # can't do anything
+                    rows = widget.rows((maxcol,), True)
+                    row_offset -= rows
+
+                if -row_offset >= rows:
+                    # must scroll further than 1 line
+                    row_offset = -(rows - 1)
+
+                self.change_focus((maxcol, maxrow), pos, row_offset, "below")
+                return None
+
+        # if all else fails, just shift the current focus.
+        self.shift_focus((maxcol, maxrow), focus_row_offset + 1)
+        return None
+
+    def _keypress_down(self, size: tuple[int, int]) -> bool | None:
+        (maxcol, maxrow) = size
+
+        middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True)
+        if middle is None:
+            return True
+
+        focus_row_offset, focus_widget, focus_pos, focus_rows, cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_bottom, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        row_offset = focus_row_offset + focus_rows
+        rows = focus_rows
+
+        # look for selectable widget below
+        pos = focus_pos
+        widget = None
+        for widget, pos, rows in fill_below:
+            if rows and widget.selectable():
+                # this one will do
+                self.change_focus((maxcol, maxrow), pos, row_offset, "above")
+                return None
+            row_offset += rows
+
+        # at this point we must scroll
+        row_offset -= 1
+        self._invalidate()
+
+        while row_offset < maxrow:
+            # need to scroll in another candidate widget
+            widget, pos = self._body.get_next(pos)
+            if widget is None:
+                # cannot scroll any further
+                return True  # keypress not handled
+            rows = widget.rows((maxcol,))
+            if rows and widget.selectable():
+                # this one will do
+                self.change_focus((maxcol, maxrow), pos, row_offset, "above")
+                return None
+            row_offset += rows
+
+        if not focus_widget.selectable() or focus_row_offset + focus_rows - 1 <= 0:
+            # just take bottom one if current is not selectable
+            # or if focus has moved out of view
+            if widget is None:
+                self.shift_focus((maxcol, maxrow), row_offset - rows)
+                return None
+            self.change_focus((maxcol, maxrow), pos, row_offset - rows, "above")
+            return None
+
+        # check if cursor will stop scroll from taking effect
+        if cursor is not None:
+            _x, y = cursor
+            if y + focus_row_offset - 1 < 0:
+                # cursor position is a problem,
+                # choose another focus
+                if widget is None:
+                    # try harder to get next widget
+                    widget, pos = self._body.get_next(pos)
+                    if widget is None:
+                        return None  # can't do anything
+                else:
+                    row_offset -= rows
+
+                if row_offset >= maxrow:
+                    # must scroll further than 1 line
+                    row_offset = maxrow - 1
+
+                self.change_focus(
+                    (maxcol, maxrow),
+                    pos,
+                    row_offset,
+                    "above",
+                )
+                return None
+
+        # if all else fails, keep the current focus.
+        self.shift_focus((maxcol, maxrow), focus_row_offset - 1)
+        return None
+
+    def _keypress_page_up(self, size: tuple[int, int]) -> bool | None:
+        (maxcol, maxrow) = size
+
+        middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True)
+        if middle is None:
+            return True
+
+        row_offset, focus_widget, focus_pos, focus_rows, cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+
+        # topmost_visible is row_offset rows above top row of
+        # focus (+ve) or -row_offset rows below top row of focus (-ve)
+        topmost_visible = row_offset
+
+        # scroll_from_row is (first match)
+        # 1. topmost visible row if focus is not selectable
+        # 2. row containing cursor if focus has a cursor
+        # 3. top row of focus widget if it is visible
+        # 4. topmost visible row otherwise
+        if not focus_widget.selectable():
+            scroll_from_row = topmost_visible
+        elif cursor is not None:
+            _x, y = cursor
+            scroll_from_row = -y
+        elif row_offset >= 0:
+            scroll_from_row = 0
+        else:
+            scroll_from_row = topmost_visible
+
+        # snap_rows is maximum extra rows to scroll when
+        # snapping to new a focus
+        snap_rows = topmost_visible - scroll_from_row
+
+        # move row_offset to the new desired value (1 "page" up)
+        row_offset = scroll_from_row + maxrow
+
+        # not used below:
+        scroll_from_row = topmost_visible = None
+
+        # gather potential target widgets and add current focus
+        t = [(row_offset, focus_widget, focus_pos, focus_rows)]
+        pos = focus_pos
+        # include widgets from calculate_visible(..)
+        for widget, pos, rows in fill_above:
+            row_offset -= rows
+            t.append((row_offset, widget, pos, rows))
+        # add newly visible ones, including within snap_rows
+        snap_region_start = len(t)
+        while row_offset > -snap_rows:
+            widget, pos = self._body.get_prev(pos)
+            if widget is None:
+                break
+            rows = widget.rows((maxcol,))
+            row_offset -= rows
+            # determine if one below puts current one into snap rgn
+            if row_offset > 0:
+                snap_region_start += 1
+            t.append((row_offset, widget, pos, rows))
+
+        # if we can't fill the top we need to adjust the row offsets
+        row_offset, _w, _p, _r = t[-1]
+        if row_offset > 0:
+            adjust = -row_offset
+            t = [(ro + adjust, w, p, r) for (ro, w, p, r) in t]
+
+        # if focus_widget (first in t) is off edge, remove it
+        row_offset, _w, _p, _r = t[0]
+        if row_offset >= maxrow:
+            del t[0]
+            snap_region_start -= 1
+
+        # we'll need this soon
+        self.update_pref_col_from_focus((maxcol, maxrow))
+
+        # choose the topmost selectable and (newly) visible widget
+        # search within snap_rows then visible region
+        search_order = list(range(snap_region_start, len(t))) + list(range(snap_region_start - 1, -1, -1))
+        # assert 0, repr((t, search_order))
+        bad_choices = []
+        cut_off_selectable_chosen = 0
+        for i in search_order:
+            row_offset, widget, pos, rows = t[i]
+            if not widget.selectable():
+                continue
+
+            if not rows:
+                continue
+
+            # try selecting this widget
+            pref_row = max(0, -row_offset)
+
+            # if completely within snap region, adjust row_offset
+            if rows + row_offset <= 0:
+                self.change_focus(
+                    (maxcol, maxrow),
+                    pos,
+                    -(rows - 1),
+                    "below",
+                    (self.pref_col, rows - 1),
+                    snap_rows - ((-row_offset) - (rows - 1)),
+                )
+            else:
+                self.change_focus(
+                    (maxcol, maxrow),
+                    pos,
+                    row_offset,
+                    "below",
+                    (self.pref_col, pref_row),
+                    snap_rows,
+                )
+
+            # if we're as far up as we can scroll, take this one
+            if fill_above and self._body.get_prev(fill_above[-1][1]) == (None, None):
+                pass  # return
+
+            # find out where that actually puts us
+            middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True)
+            act_row_offset, _ign1, _ign2, _ign3, _ign4 = middle  # pylint: disable=unpacking-non-sequence
+
+            # discard chosen widget if it will reduce scroll amount
+            # because of a fixed cursor (absolute last resort)
+            if act_row_offset > row_offset + snap_rows:
+                bad_choices.append(i)
+                continue
+            if act_row_offset < row_offset:
+                bad_choices.append(i)
+                continue
+
+            # also discard if off top edge (second last resort)
+            if act_row_offset < 0:
+                bad_choices.append(i)
+                cut_off_selectable_chosen = 1
+                continue
+
+            return None
+
+        # anything selectable is better than what follows:
+        if cut_off_selectable_chosen:
+            return None
+
+        if fill_above and focus_widget.selectable() and self._body.get_prev(fill_above[-1][1]) == (None, None):
+            # if we're at the top and have a selectable, return
+            pass  # return
+
+        # if still none found choose the topmost widget
+        good_choices = [j for j in search_order if j not in bad_choices]
+        for i in good_choices + search_order:
+            row_offset, widget, pos, rows = t[i]
+            if pos == focus_pos:
+                continue
+
+            if not rows:  # never focus a 0-height widget
+                continue
+
+            # if completely within snap region, adjust row_offset
+            if rows + row_offset <= 0:
+                snap_rows -= (-row_offset) - (rows - 1)
+                row_offset = -(rows - 1)
+
+            self.change_focus((maxcol, maxrow), pos, row_offset, "below", None, snap_rows)
+            return None
+
+        # no choices available, just shift current one
+        self.shift_focus((maxcol, maxrow), min(maxrow - 1, row_offset))
+
+        # final check for pathological case where we may fall short
+        middle, top, _bottom = self.calculate_visible((maxcol, maxrow), True)
+        act_row_offset, _ign1, pos, _ign2, _ign3 = middle  # pylint: disable=unpacking-non-sequence
+        if act_row_offset >= row_offset:
+            # no problem
+            return None
+
+        # fell short, try to select anything else above
+        if not t:
+            return None
+        _ign1, _ign2, pos, _ign3 = t[-1]
+        widget, pos = self._body.get_prev(pos)
+        if widget is None:
+            # no dice, we're stuck here
+            return None
+        # bring in only one row if possible
+        rows = widget.rows((maxcol,), True)
+        self.change_focus(
+            (maxcol, maxrow),
+            pos,
+            -(rows - 1),
+            "below",
+            (self.pref_col, rows - 1),
+            0,
+        )
+        return None
+
+    def _keypress_page_down(self, size: tuple[int, int]) -> bool | None:
+        (maxcol, maxrow) = size
+
+        middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True)
+        if middle is None:
+            return True
+
+        row_offset, focus_widget, focus_pos, focus_rows, cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_bottom, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        # bottom_edge is maxrow-focus_pos rows below top row of focus
+        bottom_edge = maxrow - row_offset
+
+        # scroll_from_row is (first match)
+        # 1. bottom edge if focus is not selectable
+        # 2. row containing cursor + 1 if focus has a cursor
+        # 3. bottom edge of focus widget if it is visible
+        # 4. bottom edge otherwise
+        if not focus_widget.selectable():
+            scroll_from_row = bottom_edge
+        elif cursor is not None:
+            _x, y = cursor
+            scroll_from_row = y + 1
+        elif bottom_edge >= focus_rows:
+            scroll_from_row = focus_rows
+        else:
+            scroll_from_row = bottom_edge
+
+        # snap_rows is maximum extra rows to scroll when
+        # snapping to new a focus
+        snap_rows = bottom_edge - scroll_from_row
+
+        # move row_offset to the new desired value (1 "page" down)
+        row_offset = -scroll_from_row
+
+        # not used below:
+        scroll_from_row = bottom_edge = None
+
+        # gather potential target widgets and add current focus
+        t = [(row_offset, focus_widget, focus_pos, focus_rows)]
+        pos = focus_pos
+        row_offset += focus_rows
+        # include widgets from calculate_visible(..)
+        for widget, pos, rows in fill_below:
+            t.append((row_offset, widget, pos, rows))
+            row_offset += rows
+        # add newly visible ones, including within snap_rows
+        snap_region_start = len(t)
+        while row_offset < maxrow + snap_rows:
+            widget, pos = self._body.get_next(pos)
+            if widget is None:
+                break
+            rows = widget.rows((maxcol,))
+            t.append((row_offset, widget, pos, rows))
+            row_offset += rows
+            # determine if one above puts current one into snap rgn
+            if row_offset < maxrow:
+                snap_region_start += 1
+
+        # if we can't fill the bottom we need to adjust the row offsets
+        row_offset, _w, _p, rows = t[-1]
+        if row_offset + rows < maxrow:
+            adjust = maxrow - (row_offset + rows)
+            t = [(ro + adjust, w, p, r) for (ro, w, p, r) in t]
+
+        # if focus_widget (first in t) is off edge, remove it
+        row_offset, _w, _p, rows = t[0]
+        if row_offset + rows <= 0:
+            del t[0]
+            snap_region_start -= 1
+
+        # we'll need this soon
+        self.update_pref_col_from_focus((maxcol, maxrow))
+
+        # choose the bottommost selectable and (newly) visible widget
+        # search within snap_rows then visible region
+        search_order = list(range(snap_region_start, len(t))) + list(range(snap_region_start - 1, -1, -1))
+        # assert 0, repr((t, search_order))
+        bad_choices = []
+        cut_off_selectable_chosen = 0
+        for i in search_order:
+            row_offset, widget, pos, rows = t[i]
+            if not widget.selectable():
+                continue
+
+            if not rows:
+                continue
+
+            # try selecting this widget
+            pref_row = min(maxrow - row_offset - 1, rows - 1)
+
+            # if completely within snap region, adjust row_offset
+            if row_offset >= maxrow:
+                self.change_focus(
+                    (maxcol, maxrow),
+                    pos,
+                    maxrow - 1,
+                    "above",
+                    (self.pref_col, 0),
+                    snap_rows + maxrow - row_offset - 1,
+                )
+            else:
+                self.change_focus(
+                    (maxcol, maxrow),
+                    pos,
+                    row_offset,
+                    "above",
+                    (self.pref_col, pref_row),
+                    snap_rows,
+                )
+
+            # find out where that actually puts us
+            middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True)
+            act_row_offset, _ign1, _ign2, _ign3, _ign4 = middle  # pylint: disable=unpacking-non-sequence
+
+            # discard chosen widget if it will reduce scroll amount
+            # because of a fixed cursor (absolute last resort)
+            if act_row_offset < row_offset - snap_rows:
+                bad_choices.append(i)
+                continue
+            if act_row_offset > row_offset:
+                bad_choices.append(i)
+                continue
+
+            # also discard if off top edge (second last resort)
+            if act_row_offset + rows > maxrow:
+                bad_choices.append(i)
+                cut_off_selectable_chosen = 1
+                continue
+
+            return None
+
+        # anything selectable is better than what follows:
+        if cut_off_selectable_chosen:
+            return None
+
+        # if still none found choose the bottommost widget
+        good_choices = [j for j in search_order if j not in bad_choices]
+        for i in good_choices + search_order:
+            row_offset, widget, pos, rows = t[i]
+            if pos == focus_pos:
+                continue
+
+            if not rows:  # never focus a 0-height widget
+                continue
+
+            # if completely within snap region, adjust row_offset
+            if row_offset >= maxrow:
+                snap_rows -= snap_rows + maxrow - row_offset - 1
+                row_offset = maxrow - 1
+
+            self.change_focus((maxcol, maxrow), pos, row_offset, "above", None, snap_rows)
+            return None
+
+        # no choices available, just shift current one
+        self.shift_focus((maxcol, maxrow), max(1 - focus_rows, row_offset))
+
+        # final check for pathological case where we may fall short
+        middle, _top, bottom = self.calculate_visible((maxcol, maxrow), True)
+        act_row_offset, _ign1, pos, _ign2, _ign3 = middle  # pylint: disable=unpacking-non-sequence
+        if act_row_offset <= row_offset:
+            # no problem
+            return None
+
+        # fell short, try to select anything else below
+        if not t:
+            return None
+        _ign1, _ign2, pos, _ign3 = t[-1]
+        widget, pos = self._body.get_next(pos)
+        if widget is None:
+            # no dice, we're stuck here
+            return None
+        # bring in only one row if possible
+        rows = widget.rows((maxcol,), True)
+        self.change_focus(
+            (maxcol, maxrow),
+            pos,
+            maxrow - 1,
+            "above",
+            (self.pref_col, 0),
+            0,
+        )
+        return None
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        event,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """
+        Pass the event to the contained widgets.
+        May change focus on button 1 press.
+        """
+        from urwid.util import is_mouse_press
+
+        (maxcol, maxrow) = size
+        middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=True)
+        if middle is None:
+            return False
+
+        _ignore, focus_widget, focus_pos, focus_rows, _cursor = middle  # pylint: disable=unpacking-non-sequence
+        trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+        _ignore, fill_below = bottom  # pylint: disable=unpacking-non-sequence
+
+        fill_above.reverse()  # fill_above is in bottom-up order
+        w_list = [*fill_above, (focus_widget, focus_pos, focus_rows), *fill_below]
+
+        wrow = -trim_top
+        for w, w_pos, w_rows in w_list:  # noqa: B007  # magic with scope
+            if wrow + w_rows > row:
+                break
+            wrow += w_rows
+        else:
+            return False
+
+        focus = focus and w == focus_widget
+        if is_mouse_press(event) and button == 1 and w.selectable():
+            self.change_focus((maxcol, maxrow), w_pos, wrow)
+
+        if not hasattr(w, "mouse_event"):
+            warnings.warn(
+                f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            return False
+
+        if w.mouse_event((maxcol,), event, button, col, row - wrow, focus):
+            return True
+
+        if is_mouse_press(event):
+            if button == 4:
+                return not self._keypress_up((maxcol, maxrow))
+
+            if button == 5:
+                return not self._keypress_down((maxcol, maxrow))
+
+        return False
+
+    def ends_visible(self, size: tuple[int, int], focus: bool = False) -> list[Literal["top", "bottom"]]:
+        """
+        Return a list that may contain ``'top'`` and/or ``'bottom'``.
+
+        i.e. this function will return one of: [], [``'top'``],
+        [``'bottom'``] or [``'top'``, ``'bottom'``].
+
+        convenience function for checking whether the top and bottom
+        of the list are visible
+        """
+        (maxcol, maxrow) = size
+        result = []
+        middle, top, bottom = self.calculate_visible((maxcol, maxrow), focus=focus)
+        if middle is None:  # empty listbox
+            return ["top", "bottom"]
+        trim_top, above = top  # pylint: disable=unpacking-non-sequence
+        trim_bottom, below = bottom  # pylint: disable=unpacking-non-sequence
+
+        if trim_bottom == 0:
+            row_offset, _w, pos, rows, _c = middle  # pylint: disable=unpacking-non-sequence
+            row_offset += rows
+            for _w, pos, rows in below:  # noqa: B007  # magic with scope
+                row_offset += rows
+            if row_offset < maxrow or (self._body.get_next(pos) == (None, None)):
+                result.append("bottom")
+
+        if trim_top == 0:
+            row_offset, _w, pos, _rows, _c = middle  # pylint: disable=unpacking-non-sequence
+            for _w, pos, rows in above:  # noqa: B007  # magic with scope
+                row_offset -= rows
+            if self._body.get_prev(pos) == (None, None):
+                result.insert(0, "top")
+
+        return result
+
+    def __iter__(self):
+        """
+        Return an iterator over the positions in this ListBox.
+
+        If self._body does not implement positions() then iterate
+        from the focus widget down to the bottom, then from above
+        the focus up to the top.  This is the best we can do with
+        a minimal list walker implementation.
+        """
+
+        if positions_fn := getattr(self._body, "positions", None):
+            yield from positions_fn()
+            return
+
+        focus_widget, focus_pos = self._body.get_focus()
+        if focus_widget is None:
+            return
+        pos = focus_pos
+        while True:
+            yield pos
+            w, pos = self._body.get_next(pos)
+            if not w:
+                break
+        pos = focus_pos
+        while True:
+            w, pos = self._body.get_prev(pos)
+            if not w:
+                break
+            yield pos
+
+    def __reversed__(self):
+        """
+        Return a reversed iterator over the positions in this ListBox.
+
+        If :attr:`body` does not implement :meth:`positions` then iterate
+        from above the focus widget up to the top, then from the focus
+        widget down to the bottom.  Note that this is not actually the
+        reverse of what `__iter__()` produces, but this is the best we can
+        do with a minimal list walker implementation.
+        """
+
+        if positions_fn := getattr(self._body, "positions", None):
+            yield from positions_fn(reverse=True)
+            return
+
+        focus_widget, focus_pos = self._body.get_focus()
+        if focus_widget is None:
+            return
+        pos = focus_pos
+        while True:
+            w, pos = self._body.get_prev(pos)
+            if not w:
+                break
+            yield pos
+        pos = focus_pos
+        while True:
+            yield pos
+            w, pos = self._body.get_next(pos)
+            if not w:
+                break
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/monitored_list.py b/python/user_packages/Python313/site-packages/urwid/widget/monitored_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc3d3240846ace782f0df7dcc0026ae1930293b0
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/monitored_list.py
@@ -0,0 +1,596 @@
+# Urwid MonitoredList class
+#    Copyright (C) 2004-2011  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+from __future__ import annotations
+
+import functools
+import typing
+import warnings
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Collection, Iterable, Iterator
+
+    from typing_extensions import Concatenate, ParamSpec, Self
+
+    ArgSpec = ParamSpec("ArgSpec")
+    Ret = typing.TypeVar("Ret")
+
+__all__ = ("MonitoredFocusList", "MonitoredList")
+
+_T = typing.TypeVar("_T")
+
+
+def _call_modified(
+    fn: Callable[Concatenate[MonitoredList, ArgSpec], Ret],
+) -> Callable[Concatenate[MonitoredList, ArgSpec], Ret]:
+    @functools.wraps(fn)
+    def call_modified_wrapper(self: MonitoredList, *args: ArgSpec.args, **kwargs: ArgSpec.kwargs) -> Ret:
+        rval = fn(self, *args, **kwargs)
+        self._modified()  # pylint: disable=protected-access
+        return rval
+
+    return call_modified_wrapper
+
+
+class MonitoredList(list[_T], typing.Generic[_T]):
+    """
+    This class can trigger a callback any time its contents are changed
+    with the usual list operations append, extend, etc.
+    """
+
+    def _modified(self) -> None:  # pylint: disable=method-hidden  # monkeypatch used
+        pass
+
+    def set_modified_callback(self, callback: Callable[[], typing.Any]) -> None:
+        """
+        Assign a callback function with no parameters that is called any
+        time the list is modified.  Callback's return value is ignored.
+
+        >>> import sys
+        >>> ml = MonitoredList([1, 2, 3])
+        >>> ml.set_modified_callback(lambda: sys.stdout.write("modified\\n"))
+        >>> ml
+        MonitoredList([1, 2, 3])
+        >>> ml.append(10)
+        modified
+        >>> len(ml)
+        4
+        >>> ml += [11, 12, 13]
+        modified
+        >>> ml[:] = ml[:2] + ml[-2:]
+        modified
+        >>> ml
+        MonitoredList([1, 2, 12, 13])
+        """
+        self._modified = callback  # monkeypatch
+
+    def __repr__(self) -> str:
+        return f"{self.__class__.__name__}({list(self)!r})"
+
+    # noinspection PyMethodParameters
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        for item in self:
+            yield None, item
+
+    @_call_modified
+    def __add__(self, __value: list[_T]) -> Self:
+        return super().__add__(__value)
+
+    @_call_modified
+    def __delitem__(self, __key: typing.SupportsIndex | slice) -> None:
+        super().__delitem__(__key)
+
+    @_call_modified
+    def __iadd__(self, __value: Iterable[_T]) -> Self:
+        return super().__iadd__(__value)
+
+    @_call_modified
+    def __rmul__(self, __value: typing.SupportsIndex) -> Self:
+        return super().__rmul__(__value)
+
+    @_call_modified
+    def __imul__(self, __value: typing.SupportsIndex) -> Self:
+        return super().__imul__(__value)
+
+    @typing.overload
+    @_call_modified
+    def __setitem__(self, __key: typing.SupportsIndex, __value: _T) -> None: ...
+
+    @typing.overload
+    @_call_modified
+    def __setitem__(self, __key: slice, __value: Iterable[_T]) -> None: ...
+
+    @_call_modified
+    def __setitem__(self, __key: typing.SupportsIndex | slice, __value: _T | Iterable[_T]) -> None:
+        super().__setitem__(__key, __value)
+
+    @_call_modified
+    def append(self, __object: _T) -> None:
+        super().append(__object)
+
+    @_call_modified
+    def extend(self, __iterable: Iterable[_T]) -> None:
+        super().extend(__iterable)
+
+    @_call_modified
+    def pop(self, __index: typing.SupportsIndex = -1) -> _T:
+        return super().pop(__index)
+
+    @_call_modified
+    def insert(self, __index: typing.SupportsIndex, __object: _T) -> None:
+        super().insert(__index, __object)
+
+    @_call_modified
+    def remove(self, __value: _T) -> None:
+        super().remove(__value)
+
+    @_call_modified
+    def reverse(self) -> None:
+        super().reverse()
+
+    @_call_modified
+    def sort(self, *, key: Callable[[_T], typing.Any] | None = None, reverse: bool = False) -> None:
+        super().sort(key=key, reverse=reverse)
+
+    @_call_modified
+    def clear(self) -> None:
+        super().clear()
+
+
+class MonitoredFocusList(MonitoredList[_T], typing.Generic[_T]):
+    """
+    This class can trigger a callback any time its contents are modified,
+    before and/or after modification, and any time the focus index is changed.
+    """
+
+    def __init__(self, *args, focus: int = 0, **kwargs) -> None:
+        """
+        This is a list that tracks one item as the focus item.  If items
+        are inserted or removed it will update the focus.
+
+        >>> ml = MonitoredFocusList([10, 11, 12, 13, 14], focus=3)
+        >>> ml
+        MonitoredFocusList([10, 11, 12, 13, 14], focus=3)
+        >>> del ml[1]
+        >>> ml
+        MonitoredFocusList([10, 12, 13, 14], focus=2)
+        >>> ml[:2] = [50, 51, 52, 53]
+        >>> ml
+        MonitoredFocusList([50, 51, 52, 53, 13, 14], focus=4)
+        >>> ml[4] = 99
+        >>> ml
+        MonitoredFocusList([50, 51, 52, 53, 99, 14], focus=4)
+        >>> ml[:] = []
+        >>> ml
+        MonitoredFocusList([], focus=None)
+        """
+
+        super().__init__(*args, **kwargs)
+
+        self._focus = focus
+        self._focus_modified = lambda ml, indices, new_items: None
+
+    def __repr__(self) -> str:
+        return f"{self.__class__.__name__}({list(self)!r}, focus={self.focus!r})"
+
+    @property
+    def focus(self) -> int | None:
+        """
+        Get/set the focus index.  This value is read as None when the list
+        is empty, and may only be set to a value between 0 and len(self)-1
+        or an IndexError will be raised.
+
+        Return the index of the item "in focus" or None if
+        the list is empty.
+
+        >>> MonitoredFocusList([1, 2, 3], focus=2).focus
+        2
+        >>> MonitoredFocusList().focus
+        """
+        if not self:
+            return None
+        return self._focus
+
+    @focus.setter
+    def focus(self, index: int) -> None:
+        """
+        index -- index into this list, any index out of range will
+            raise an IndexError, except when the list is empty and
+            the index passed is ignored.
+
+        This function may call self._focus_changed when the focus
+        is modified, passing the new focus position to the
+        callback just before changing the old focus setting.
+        That method may be overridden on the
+        instance with set_focus_changed_callback().
+
+        >>> ml = MonitoredFocusList([9, 10, 11])
+        >>> ml.focus = 2
+        ... ml.focus
+        2
+        >>> ml.focus = 0
+        ... ml.focus
+        0
+        >>> ml.focus = -2
+        Traceback (most recent call last):
+        ...
+        IndexError: focus index is out of range: -2
+        """
+        if not self:
+            self._focus = 0
+            return
+        if not isinstance(index, int):
+            raise TypeError("index must be an integer")
+        if index < 0 or index >= len(self):
+            raise IndexError(f"focus index is out of range: {index}")
+
+        if index != self._focus:
+            self._focus_changed(index)
+        self._focus = index
+
+    def _get_focus(self) -> int | None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}._get_focus` is deprecated, "
+            f"please use `{self.__class__.__name__}.focus` property."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=3,
+        )
+        return self.focus
+
+    def _set_focus(self, index: int) -> None:
+        warnings.warn(
+            f"method `{self.__class__.__name__}._set_focus` is deprecated, "
+            f"please use `{self.__class__.__name__}.focus` property."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=3,
+        )
+        self.focus = index
+
+    def _focus_changed(self, new_focus: int) -> None:  # pylint: disable=method-hidden  # monkeypatch used
+        pass
+
+    def set_focus_changed_callback(self, callback: Callable[[int], typing.Any]) -> None:
+        """
+        Assign a callback to be called when the focus index changes
+        for any reason.  The callback is in the form:
+
+        callback(new_focus)
+        new_focus -- new focus index
+
+        >>> import sys
+        >>> ml = MonitoredFocusList([1, 2, 3], focus=1)
+        >>> ml.set_focus_changed_callback(lambda f: sys.stdout.write("focus: %d\\n" % (f,)))
+        >>> ml
+        MonitoredFocusList([1, 2, 3], focus=1)
+        >>> ml.append(10)
+        >>> ml.insert(1, 11)
+        focus: 2
+        >>> ml
+        MonitoredFocusList([1, 11, 2, 3, 10], focus=2)
+        >>> del ml[:2]
+        focus: 0
+        >>> ml[:0] = [12, 13, 14]
+        focus: 3
+        >>> ml.focus = 5
+        focus: 5
+        >>> ml
+        MonitoredFocusList([12, 13, 14, 2, 3, 10], focus=5)
+        """
+        self._focus_changed = callback  # Monkeypatch
+
+    def _validate_contents_modified(  # pylint: disable=method-hidden  # monkeypatch used
+        self,
+        indices: tuple[int, int, int],
+        new_items: Collection[_T],
+    ) -> int | None:
+        return None
+
+    def set_validate_contents_modified(self, callback: Callable[[tuple[int, int, int], Collection[_T]], int | None]):
+        """
+        Assign a callback function to handle validating changes to the list.
+        This may raise an exception if the change should not be performed.
+        It may also return an integer position to be the new focus after the
+        list is modified, or None to use the default behaviour.
+
+        The callback is in the form:
+
+        callback(indices, new_items)
+        indices -- a (start, stop, step) tuple whose range covers the
+            items being modified
+        new_items -- an iterable of items replacing those at range(*indices),
+            empty if items are being removed, if step==1 this list may
+            contain any number of items
+        """
+        self._validate_contents_modified = callback  # Monkeypatch
+
+    def _adjust_focus_on_contents_modified(self, slc: slice, new_items: Collection[_T] = ()) -> int:
+        """
+        Default behaviour is to move the focus to the item following
+        any removed items, unless that item was simply replaced.
+
+        Failing that choose the last item in the list.
+
+        returns focus position for after change is applied
+        """
+        num_new_items = len(new_items)
+        start, stop, step = indices = slc.indices(len(self))
+        num_removed = len(list(range(*indices)))
+
+        focus = self._validate_contents_modified(indices, new_items)
+        if focus is not None:
+            return focus
+
+        focus = self._focus
+        if step == 1:
+            if start + num_new_items <= focus < stop:
+                focus = stop
+            # adjust for added/removed items
+            if stop <= focus:
+                focus += num_new_items - (stop - start)
+
+        else:  # noqa: PLR5501  # pylint: disable=else-if-used  # readability
+            if not num_new_items:
+                # extended slice being removed
+                if focus in range(start, stop, step):
+                    focus += 1
+
+                # adjust for removed items
+                focus -= len(list(range(start, min(focus, stop), step)))
+
+        return min(focus, len(self) + num_new_items - num_removed - 1)
+
+    # override all the list methods that modify the list
+
+    def __delitem__(self, y: int | slice) -> None:
+        """
+        >>> ml = MonitoredFocusList([0, 1, 2, 3, 4], focus=2)
+        >>> del ml[3]
+        >>> ml
+        MonitoredFocusList([0, 1, 2, 4], focus=2)
+        >>> del ml[-1]
+        >>> ml
+        MonitoredFocusList([0, 1, 2], focus=2)
+        >>> del ml[0]
+        >>> ml
+        MonitoredFocusList([1, 2], focus=1)
+        >>> del ml[1]
+        >>> ml
+        MonitoredFocusList([1], focus=0)
+        >>> del ml[0]
+        >>> ml
+        MonitoredFocusList([], focus=None)
+        >>> ml = MonitoredFocusList([5, 4, 6, 4, 5, 4, 6, 4, 5], focus=4)
+        >>> del ml[1::2]
+        >>> ml
+        MonitoredFocusList([5, 6, 5, 6, 5], focus=2)
+        >>> del ml[::2]
+        >>> ml
+        MonitoredFocusList([6, 6], focus=1)
+        >>> ml = MonitoredFocusList([0, 1, 2, 3, 4, 6, 7], focus=2)
+        >>> del ml[-2:]
+        >>> ml
+        MonitoredFocusList([0, 1, 2, 3, 4], focus=2)
+        >>> del ml[-4:-2]
+        >>> ml
+        MonitoredFocusList([0, 3, 4], focus=1)
+        >>> del ml[:]
+        >>> ml
+        MonitoredFocusList([], focus=None)
+        """
+        if isinstance(y, slice):
+            focus = self._adjust_focus_on_contents_modified(y)
+        else:
+            focus = self._adjust_focus_on_contents_modified(slice(y, y + 1 or None))
+        super().__delitem__(y)
+        self.focus = focus
+
+    @typing.overload
+    def __setitem__(self, i: int, y: _T) -> None: ...
+
+    @typing.overload
+    def __setitem__(self, i: slice, y: Collection[_T]) -> None: ...
+
+    def __setitem__(self, i: int | slice, y: _T | Collection[_T]) -> None:
+        """
+        >>> def modified(indices, new_items):
+        ...     print(f"range{indices!r} <- {new_items!r}")
+        >>> ml = MonitoredFocusList([0, 1, 2, 3], focus=2)
+        >>> ml.set_validate_contents_modified(modified)
+        >>> ml[0] = 9
+        range(0, 1, 1) <- [9]
+        >>> ml[2] = 6
+        range(2, 3, 1) <- [6]
+        >>> ml.focus
+        2
+        >>> ml[-1] = 8
+        range(3, 4, 1) <- [8]
+        >>> ml
+        MonitoredFocusList([9, 1, 6, 8], focus=2)
+        >>> ml[1::2] = [12, 13]
+        range(1, 4, 2) <- [12, 13]
+        >>> ml[::2] = [10, 11]
+        range(0, 4, 2) <- [10, 11]
+        >>> ml[-3:-1] = [21, 22, 23]
+        range(1, 3, 1) <- [21, 22, 23]
+        >>> ml
+        MonitoredFocusList([10, 21, 22, 23, 13], focus=2)
+        >>> ml[:] = []
+        range(0, 5, 1) <- []
+        >>> ml
+        MonitoredFocusList([], focus=None)
+        """
+        if isinstance(i, slice):
+            focus = self._adjust_focus_on_contents_modified(i, y)
+        else:
+            focus = self._adjust_focus_on_contents_modified(slice(i, i + 1 or None), [y])
+        super().__setitem__(i, y)
+        self.focus = focus
+
+    def __imul__(self, n: int):
+        """
+        >>> def modified(indices, new_items):
+        ...     print(f"range{indices!r} <- {list(new_items)!r}")
+        >>> ml = MonitoredFocusList([0, 1, 2], focus=2)
+        >>> ml.set_validate_contents_modified(modified)
+        >>> ml *= 3
+        range(3, 3, 1) <- [0, 1, 2, 0, 1, 2]
+        >>> ml
+        MonitoredFocusList([0, 1, 2, 0, 1, 2, 0, 1, 2], focus=2)
+        >>> ml *= 0
+        range(0, 9, 1) <- []
+        >>> print(ml.focus)
+        None
+        """
+        if n > 0:
+            focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), list(self) * (n - 1))
+        else:  # all contents are being removed
+            focus = self._adjust_focus_on_contents_modified(slice(0, len(self)))
+        rval = super().__imul__(n)
+        self.focus = focus
+        return rval
+
+    def append(self, item: _T) -> None:
+        """
+        >>> def modified(indices, new_items):
+        ...     print(f"range{indices!r} <- {new_items!r}")
+        >>> ml = MonitoredFocusList([0, 1, 2], focus=2)
+        >>> ml.set_validate_contents_modified(modified)
+        >>> ml.append(6)
+        range(3, 3, 1) <- [6]
+        """
+        focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), [item])
+        super().append(item)
+        self.focus = focus
+
+    def extend(self, items: Collection[_T]) -> None:
+        """
+        >>> def modified(indices, new_items):
+        ...     print(f"range{indices!r} <- {list(new_items)!r}")
+        >>> ml = MonitoredFocusList([0, 1, 2], focus=2)
+        >>> ml.set_validate_contents_modified(modified)
+        >>> ml.extend((6, 7, 8))
+        range(3, 3, 1) <- [6, 7, 8]
+        """
+        focus = self._adjust_focus_on_contents_modified(slice(len(self), len(self)), items)
+        super().extend(items)
+        self.focus = focus
+
+    def insert(self, index: int, item: _T) -> None:
+        """
+        >>> ml = MonitoredFocusList([0, 1, 2, 3], focus=2)
+        >>> ml.insert(-1, -1)
+        >>> ml
+        MonitoredFocusList([0, 1, 2, -1, 3], focus=2)
+        >>> ml.insert(0, -2)
+        >>> ml
+        MonitoredFocusList([-2, 0, 1, 2, -1, 3], focus=3)
+        >>> ml.insert(3, -3)
+        >>> ml
+        MonitoredFocusList([-2, 0, 1, -3, 2, -1, 3], focus=4)
+        """
+        focus = self._adjust_focus_on_contents_modified(slice(index, index), [item])
+        super().insert(index, item)
+        self.focus = focus
+
+    def pop(self, index: int = -1) -> _T:
+        """
+        >>> ml = MonitoredFocusList([-2, 0, 1, -3, 2, 3], focus=4)
+        >>> ml.pop(3)
+        -3
+        >>> ml
+        MonitoredFocusList([-2, 0, 1, 2, 3], focus=3)
+        >>> ml.pop(0)
+        -2
+        >>> ml
+        MonitoredFocusList([0, 1, 2, 3], focus=2)
+        >>> ml.pop(-1)
+        3
+        >>> ml
+        MonitoredFocusList([0, 1, 2], focus=2)
+        >>> ml.pop(2)
+        2
+        >>> ml
+        MonitoredFocusList([0, 1], focus=1)
+        """
+        focus = self._adjust_focus_on_contents_modified(slice(index, index + 1 or None))
+        rval = super().pop(index)
+        self.focus = focus
+        return rval
+
+    def remove(self, value: _T) -> None:
+        """
+        >>> ml = MonitoredFocusList([-2, 0, 1, -3, 2, -1, 3], focus=4)
+        >>> ml.remove(-3)
+        >>> ml
+        MonitoredFocusList([-2, 0, 1, 2, -1, 3], focus=3)
+        >>> ml.remove(-2)
+        >>> ml
+        MonitoredFocusList([0, 1, 2, -1, 3], focus=2)
+        >>> ml.remove(3)
+        >>> ml
+        MonitoredFocusList([0, 1, 2, -1], focus=2)
+        """
+        index = self.index(value)
+        focus = self._adjust_focus_on_contents_modified(slice(index, index + 1 or None))
+        super().remove(value)
+        self.focus = focus
+
+    def reverse(self) -> None:
+        """
+        >>> ml = MonitoredFocusList([0, 1, 2, 3, 4], focus=1)
+        >>> ml.reverse()
+        >>> ml
+        MonitoredFocusList([4, 3, 2, 1, 0], focus=3)
+        """
+        rval = super().reverse()
+        self.focus = max(0, len(self) - self._focus - 1)
+        return rval
+
+    def sort(self, **kwargs) -> None:
+        """
+        >>> ml = MonitoredFocusList([-2, 0, 1, -3, 2, -1, 3], focus=4)
+        >>> ml.sort()
+        >>> ml
+        MonitoredFocusList([-3, -2, -1, 0, 1, 2, 3], focus=5)
+        """
+        if not self:
+            return None
+        value = self[self._focus]
+        rval = super().sort(**kwargs)
+        self.focus = self.index(value)
+        return rval
+
+    if hasattr(list, "clear"):
+
+        def clear(self) -> None:
+            focus = self._adjust_focus_on_contents_modified(slice(0, 0))
+            super().clear()
+            self.focus = focus
+
+
+def _test():
+    import doctest
+
+    doctest.testmod()
+
+
+if __name__ == "__main__":
+    _test()
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/overlay.py b/python/user_packages/Python313/site-packages/urwid/widget/overlay.py
new file mode 100644
index 0000000000000000000000000000000000000000..90151465b977613e6cd8eeae06ee2e731cc06f39
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/overlay.py
@@ -0,0 +1,910 @@
+from __future__ import annotations
+
+import typing
+import warnings
+from collections.abc import MutableSequence
+
+from urwid.canvas import CanvasOverlay, CompositeCanvas
+from urwid.split_repr import remove_defaults
+
+from .constants import (
+    RELATIVE_100,
+    Align,
+    Sizing,
+    VAlign,
+    WHSettings,
+    WrapMode,
+    normalize_align,
+    normalize_height,
+    normalize_valign,
+    normalize_width,
+    simplify_align,
+    simplify_height,
+    simplify_valign,
+    simplify_width,
+)
+from .container import WidgetContainerListContentsMixin, WidgetContainerMixin
+from .filler import calculate_top_bottom_filler
+from .padding import calculate_left_right_padding
+from .widget import Widget, WidgetError, WidgetWarning
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterator, Sequence
+
+    from typing_extensions import Literal
+
+
+TopWidget = typing.TypeVar("TopWidget")
+BottomWidget = typing.TypeVar("BottomWidget")
+
+
+class OverlayError(WidgetError):
+    """Overlay specific errors."""
+
+
+class OverlayWarning(WidgetWarning):
+    """Overlay specific warnings."""
+
+
+def _check_widget_subclass(widget: Widget) -> None:
+    if not isinstance(widget, Widget):
+        obj_class_path = f"{widget.__class__.__module__}.{widget.__class__.__name__}"
+        warnings.warn(
+            f"{obj_class_path} is not subclass of Widget",
+            DeprecationWarning,
+            stacklevel=3,
+        )
+
+
+class OverlayOptions(typing.NamedTuple):
+    align: Align | Literal[WHSettings.RELATIVE]
+    align_amount: int | None
+    width_type: WHSettings
+    width_amount: int | None
+    min_width: int | None
+    left: int
+    right: int
+    valign_type: VAlign | Literal[WHSettings.RELATIVE]
+    valign_amount: int | None
+    height_type: WHSettings
+    height_amount: int | None
+    min_height: int | None
+    top: int
+    bottom: int
+
+
+class Overlay(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin, typing.Generic[TopWidget, BottomWidget]):
+    """Overlay contains two widgets and renders one on top of the other.
+
+    Top widget can be Box, Flow or Fixed.
+    Bottom widget should be Box.
+    """
+
+    _selectable = True
+
+    _DEFAULT_BOTTOM_OPTIONS = OverlayOptions(
+        align=Align.LEFT,
+        align_amount=None,
+        width_type=WHSettings.RELATIVE,
+        width_amount=100,
+        min_width=None,
+        left=0,
+        right=0,
+        valign_type=VAlign.TOP,
+        valign_amount=None,
+        height_type=WHSettings.RELATIVE,
+        height_amount=100,
+        min_height=None,
+        top=0,
+        bottom=0,
+    )
+
+    def __init__(
+        self,
+        top_w: TopWidget,
+        bottom_w: BottomWidget,
+        align: (
+            Literal["left", "center", "right"]
+            | Align
+            | tuple[Literal["relative", "fixed left", "fixed right", WHSettings.RELATIVE], int]
+        ),
+        width: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None,
+        valign: (
+            Literal["top", "middle", "bottom"]
+            | VAlign
+            | tuple[Literal["relative", "fixed top", "fixed bottom", WHSettings.RELATIVE], int]
+        ),
+        height: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None,
+        min_width: int | None = None,
+        min_height: int | None = None,
+        left: int = 0,
+        right: int = 0,
+        top: int = 0,
+        bottom: int = 0,
+    ) -> None:
+        """
+        :param top_w: a flow, box or fixed widget to overlay "on top".
+        :type top_w: Widget
+        :param bottom_w: a box widget to appear "below" previous widget.
+        :type bottom_w: Widget
+        :param align: alignment, one of ``'left'``, ``'center'``, ``'right'`` or
+            (``'relative'``, *percentage* 0=left 100=right)
+        :type align: Literal["left", "center", "right"] | tuple[Literal["relative"], int]
+        :param width: width type, one of:
+            ``'pack'``
+              if *top_w* is a fixed widget
+            *given width*
+              integer number of columns wide
+            (``'relative'``, *percentage of total width*)
+              make *top_w* width related to container width
+        :type width: Literal["pack"] | int | tuple[Literal["relative"], int]
+        :param valign: alignment mode, one of ``'top'``, ``'middle'``, ``'bottom'`` or
+            (``'relative'``, *percentage* 0=top 100=bottom)
+        :type valign: Literal["top", "middle", "bottom"] | tuple[Literal["relative"], int]
+        :param height: one of:
+            ``'pack'``
+              if *top_w* is a flow or fixed widget
+            *given height*
+              integer number of rows high
+            (``'relative'``, *percentage of total height*)
+              make *top_w* height related to container height
+        :type height: Literal["pack"] | int | tuple[Literal["relative"], int]
+        :param min_width: the minimum number of columns for *top_w* when width is not fixed.
+        :type min_width: int
+        :param min_height: minimum number of rows for *top_w* when height is not fixed.
+        :type min_height: int
+        :param left: a fixed number of columns to add on the left.
+        :type left: int
+        :param right: a fixed number of columns to add on the right.
+        :type right: int
+        :param top: a fixed number of rows to add on the top.
+        :type top: int
+        :param bottom: a fixed number of rows to add on the bottom.
+        :type bottom: int
+
+        Overlay widgets behave similarly to :class:`Padding` and :class:`Filler`
+        widgets when determining the size and position of *top_w*. *bottom_w* is
+        always rendered the full size available "below" *top_w*.
+        """
+        super().__init__()
+
+        self.top_w = top_w
+        self.bottom_w = bottom_w
+
+        self.set_overlay_parameters(align, width, valign, height, min_width, min_height, left, right, top, bottom)
+
+        _check_widget_subclass(top_w)
+        _check_widget_subclass(bottom_w)
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Actual widget sizing.
+
+        :returns: Sizing information depends on the top widget sizing and sizing parameters.
+        :rtype: frozenset[Sizing]
+
+        Rules:
+        * BOX sizing is always supported provided by the bottom widget
+        * FLOW sizing is supported if top widget has:
+        * * PACK height type and FLOW supported by the TOP widget
+        * * BOX supported by TOP widget AND height amount AND height type GIVEN of min_height
+        * FIXED sizing is supported if top widget has:
+        * * PACK width type and FIXED supported by the TOP widget
+        * * width amount and GIVEN width or min_width AND:
+        * * * FLOW supported by the TOP widget AND PACK height type
+        * * * BOX supported by the TOP widget AND height_amount and GIVEN height or min height
+        """
+        sizing = {Sizing.BOX}
+        top_sizing = self.top_w.sizing()
+        if self.width_type == WHSettings.PACK:
+            if Sizing.FIXED in top_sizing:
+                sizing.add(Sizing.FIXED)
+            else:
+                warnings.warn(
+                    f"Top widget {self.top_w} should support sizing {Sizing.FIXED.upper()} "
+                    f"for width type {WHSettings.PACK.upper()}",
+                    OverlayWarning,
+                    stacklevel=3,
+                )
+
+        elif self.height_type == WHSettings.PACK:
+            if Sizing.FLOW in top_sizing:
+                sizing.add(Sizing.FLOW)
+
+                if self.width_amount and (self.width_type == WHSettings.GIVEN or self.min_width):
+                    sizing.add(Sizing.FIXED)
+            else:
+                warnings.warn(
+                    f"Top widget {self.top_w} should support sizing {Sizing.FLOW.upper()} "
+                    f"for height type {self.height_type.upper()}",
+                    OverlayWarning,
+                    stacklevel=3,
+                )
+
+        elif self.height_amount and (self.height_type == WHSettings.GIVEN or self.min_height):
+            if Sizing.BOX in top_sizing:
+                sizing.add(Sizing.FLOW)
+                if self.width_amount and (self.width_type == WHSettings.GIVEN or self.min_width):
+                    sizing.add(Sizing.FIXED)
+            else:
+                warnings.warn(
+                    f"Top widget {self.top_w} should support sizing {Sizing.BOX.upper()} "
+                    f"for height type {self.height_type.upper()}",
+                    OverlayWarning,
+                    stacklevel=3,
+                )
+
+        return frozenset(sizing)
+
+    def pack(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int] = (),
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        if size:
+            return super().pack(size, focus)
+
+        extra_cols = (self.left or 0) + (self.right or 0)
+        extra_rows = (self.top or 0) + (self.bottom or 0)
+
+        if self.width_type == WHSettings.PACK:
+            cols, rows = self.top_w.pack((), focus)
+            return cols + extra_cols, rows + extra_rows
+
+        if not self.width_amount:
+            raise OverlayError(
+                f"Requested FIXED render for {self.top_w} with "
+                f"width_type={self.width_type.upper()}, "
+                f"width_amount={self.width_amount!r}, "
+                f"height_type={self.height_type.upper()}, "
+                f"height_amount={self.height_amount!r}"
+                f"min_width={self.min_width!r}, "
+                f"min_height={self.min_height!r}"
+            )
+
+        if self.width_type == WHSettings.GIVEN:
+            w_cols = self.width_amount
+            cols = w_cols + extra_cols
+        elif self.width_type == WHSettings.RELATIVE and self.min_width:
+            w_cols = self.min_width
+            cols = int(w_cols * 100 / self.width_amount + 0.5)
+        else:
+            raise OverlayError(
+                f"Requested FIXED render for {self.top_w} with "
+                f"width_type={self.width_type.upper()}, "
+                f"width_amount={self.width_amount!r}, "
+                f"height_type={self.height_type.upper()}, "
+                f"height_amount={self.height_amount!r}"
+                f"min_width={self.min_width!r}, "
+                f"min_height={self.min_height!r}"
+            )
+
+        if self.height_type == WHSettings.PACK:
+            return cols, self.top_w.rows((w_cols,), focus) + extra_rows
+
+        if not self.height_amount:
+            raise OverlayError(
+                f"Requested FIXED render for {self.top_w} with "
+                f"width_type={self.width_type.upper()}, "
+                f"width_amount={self.width_amount!r}, "
+                f"height_type={self.height_type.upper()}, "
+                f"height_amount={self.height_amount!r}"
+                f"min_width={self.min_width!r}, "
+                f"min_height={self.min_height!r}"
+            )
+
+        if self.height_type == WHSettings.GIVEN:
+            return cols, self.height_amount + extra_rows
+
+        if self.height_type == WHSettings.RELATIVE and self.min_height:
+            return cols, int(self.min_height * 100 / self.height_amount + 0.5)
+
+        raise OverlayError(
+            f"Requested FIXED render for {self.top_w} with "
+            f"width_type={self.width_type.upper()}, "
+            f"width_amount={self.width_amount!r}, "
+            f"height_type={self.height_type.upper()}, "
+            f"height_amount={self.height_amount!r}"
+            f"min_width={self.min_width!r}, "
+            f"min_height={self.min_height!r}"
+        )
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """Widget rows amount for FLOW sizing."""
+        extra_height = (self.top or 0) + (self.bottom or 0)
+        if self.height_type == WHSettings.GIVEN:
+            return self.height_amount + extra_height
+        if self.height_type == WHSettings.RELATIVE and self.min_height:
+            return int(self.min_height * 100 / self.height_amount + 0.5)
+
+        if self.height_type == WHSettings.PACK:
+            extra_height = (self.top or 0) + (self.bottom or 0)
+            if self.width_type == WHSettings.GIVEN and self.width_amount:
+                return self.top_w.rows((self.width_amount,), focus) + extra_height
+            if self.width_type == WHSettings.RELATIVE:
+                width = max(int(size[0] * self.width_amount / 100 + 0.5), (self.min_width or 0))
+                return self.top_w.rows((width,), focus) + extra_height
+
+        raise OverlayError(
+            f"Requested rows for {self.top_w} with size {size!r}"
+            f"width_type={self.width_type.upper()}, "
+            f"width_amount={self.width_amount!r}, "
+            f"height_type={self.height_type.upper()}, "
+            f"height_amount={self.height_amount!r}"
+            f"min_width={self.min_width!r}, "
+            f"min_height={self.min_height!r}"
+        )
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "top_w": self.top_w,
+            "bottom_w": self.bottom_w,
+            "align": self.align,
+            "width": self.width,
+            "valign": self.valign,
+            "height": self.height,
+            "min_width": self.min_width,
+            "min_height": self.min_height,
+            "left": self.left,
+            "right": self.right,
+            "top": self.top,
+            "bottom": self.bottom,
+        }
+        return remove_defaults(attrs, Overlay.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        yield "top", self.top_w
+        yield "bottom", self.bottom_w
+        yield "align", self.align
+        yield "width", self.width
+        yield "valign", self.valign
+        yield "height", self.height
+        yield "min_width", self.min_width
+        yield "min_height", self.min_height
+        yield "left", self.left
+        yield "right", self.right
+        yield "top", self.top
+        yield "bottom", self.bottom
+
+    @property
+    def align(self) -> Align | tuple[Literal[WHSettings.RELATIVE], int]:
+        return simplify_align(self.align_type, self.align_amount)
+
+    @property
+    def width(
+        self,
+    ) -> (
+        Literal[WHSettings.CLIP, WHSettings.PACK]
+        | int
+        | tuple[Literal[WHSettings.RELATIVE], int]
+        | tuple[Literal[WHSettings.WEIGHT], int | float]
+    ):
+        return simplify_width(self.width_type, self.width_amount)
+
+    @property
+    def valign(self) -> VAlign | tuple[Literal[WHSettings.RELATIVE], int]:
+        return simplify_valign(self.valign_type, self.valign_amount)
+
+    @property
+    def height(
+        self,
+    ) -> (
+        int
+        | Literal[WHSettings.FLOW, WHSettings.PACK]
+        | tuple[Literal[WHSettings.RELATIVE], int]
+        | tuple[Literal[WHSettings.WEIGHT], int | float]
+    ):
+        return simplify_height(self.height_type, self.height_amount)
+
+    @staticmethod
+    def options(
+        align_type: Literal["left", "center", "right", "relative", WHSettings.RELATIVE] | Align,
+        align_amount: int | None,
+        width_type: Literal["clip", "pack", "relative", "given"] | WHSettings,
+        width_amount: int | None,
+        valign_type: Literal["top", "middle", "bottom", "relative", WHSettings.RELATIVE] | VAlign,
+        valign_amount: int | None,
+        height_type: Literal["flow", "pack", "relative", "given"] | WHSettings,
+        height_amount: int | None,
+        min_width: int | None = None,
+        min_height: int | None = None,
+        left: int = 0,
+        right: int = 0,
+        top: int = 0,
+        bottom: int = 0,
+    ) -> OverlayOptions:
+        """
+        Return a new options tuple for use in this Overlay's .contents mapping.
+
+        This is the common container API to create options for replacing the
+        top widget of this Overlay.  It is provided for completeness
+        but is not necessarily the easiest way to change the overlay parameters.
+        See also :meth:`.set_overlay_parameters`
+        """
+        if align_type in {Align.LEFT, Align.CENTER, Align.RIGHT}:
+            align = Align(align_type)
+        elif align_type == WHSettings.RELATIVE:
+            align = WHSettings.RELATIVE
+        else:
+            raise ValueError(f"Unknown alignment type {align_type!r}")
+
+        if valign_type in {VAlign.TOP, VAlign.MIDDLE, VAlign.BOTTOM}:
+            valign = VAlign(valign_type)
+        elif valign_type == WHSettings.RELATIVE:
+            valign = WHSettings.RELATIVE
+        else:
+            raise ValueError(f"Unknown vertical alignment type {valign_type!r}")
+
+        return OverlayOptions(
+            align,
+            align_amount,
+            WHSettings(width_type),
+            width_amount,
+            min_width,
+            left,
+            right,
+            valign,
+            valign_amount,
+            WHSettings(height_type),
+            height_amount,
+            min_height,
+            top,
+            bottom,
+        )
+
+    def set_overlay_parameters(
+        self,
+        align: (
+            Literal["left", "center", "right"]
+            | Align
+            | tuple[Literal["relative", "fixed left", "fixed right", WHSettings.RELATIVE], int]
+        ),
+        width: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None,
+        valign: (
+            Literal["top", "middle", "bottom"]
+            | VAlign
+            | tuple[Literal["relative", "fixed top", "fixed bottom", WHSettings.RELATIVE], int]
+        ),
+        height: Literal["pack", WHSettings.PACK] | int | tuple[Literal["relative", WHSettings.RELATIVE], int] | None,
+        min_width: int | None = None,
+        min_height: int | None = None,
+        left: int = 0,
+        right: int = 0,
+        top: int = 0,
+        bottom: int = 0,
+    ) -> None:
+        """
+        Adjust the overlay size and position parameters.
+
+        See :class:`__init__() ` for a description of the parameters.
+        """
+
+        # convert obsolete parameters 'fixed ...':
+        if isinstance(align, tuple):
+            if align[0] == "fixed left":
+                left = align[1]
+                normalized_align = Align.LEFT
+            elif align[0] == "fixed right":
+                right = align[1]
+                normalized_align = Align.RIGHT
+            else:
+                normalized_align = align
+        else:
+            normalized_align = Align(align)
+
+        if isinstance(width, tuple):
+            if width[0] == "fixed left":
+                left = width[1]
+                width = RELATIVE_100
+            elif width[0] == "fixed right":
+                right = width[1]
+                width = RELATIVE_100
+
+        if isinstance(valign, tuple):
+            if valign[0] == "fixed top":
+                top = valign[1]
+                normalized_valign = VAlign.TOP
+            elif valign[0] == "fixed bottom":
+                bottom = valign[1]
+                normalized_valign = VAlign.BOTTOM
+            else:
+                normalized_valign = valign
+
+        elif not isinstance(valign, (VAlign, str)):
+            raise OverlayError(f"invalid valign: {valign!r}")
+
+        else:
+            normalized_valign = VAlign(valign)
+
+        if isinstance(height, tuple):
+            if height[0] == "fixed bottom":
+                bottom = height[1]
+                height = RELATIVE_100
+            elif height[0] == "fixed top":
+                top = height[1]
+                height = RELATIVE_100
+
+        if width is None:  # more obsolete values accepted
+            width = WHSettings.PACK
+        if height is None:
+            height = WHSettings.PACK
+
+        align_type, align_amount = normalize_align(normalized_align, OverlayError)
+        width_type, width_amount = normalize_width(width, OverlayError)
+        valign_type, valign_amount = normalize_valign(normalized_valign, OverlayError)
+        height_type, height_amount = normalize_height(height, OverlayError)
+
+        if height_type in {WHSettings.GIVEN, WHSettings.PACK}:
+            min_height = None
+
+        # use container API to set the parameters
+        self.contents[1] = (
+            self.top_w,
+            self.options(
+                align_type,
+                align_amount,
+                width_type,
+                width_amount,
+                valign_type,
+                valign_amount,
+                height_type,
+                height_amount,
+                min_width,
+                min_height,
+                left,
+                right,
+                top,
+                bottom,
+            ),
+        )
+
+    def selectable(self) -> bool:
+        """Return selectable from top_w."""
+        return self.top_w.selectable()
+
+    def keypress(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        key: str,
+    ) -> str | None:
+        """Pass keypress to top_w."""
+        real_size = self.pack(size, True)
+        return self.top_w.keypress(
+            self.top_w_size(real_size, *self.calculate_padding_filler(real_size, True)),
+            key,
+        )
+
+    @property
+    def focus(self) -> TopWidget:
+        """
+        Read-only property returning the child widget in focus for
+        container widgets.  This default implementation
+        always returns ``None``, indicating that this widget has no children.
+        """
+        return self.top_w
+
+    @property
+    def focus_position(self) -> Literal[1]:
+        """
+        Return the top widget position (currently always 1).
+        """
+        return 1
+
+    @focus_position.setter
+    def focus_position(self, position: int) -> None:
+        """
+        Set the widget in focus.  Currently only position 0 is accepted.
+
+        position -- index of child widget to be made focus
+        """
+        if position != 1:
+            raise IndexError(f"Overlay widget focus_position currently must always be set to 1, not {position}")
+
+    @property
+    def contents(self) -> MutableSequence[tuple[TopWidget | BottomWidget, OverlayOptions]]:
+        """
+        a list-like object similar to::
+
+            [(bottom_w, bottom_options)),
+             (top_w, top_options)]
+
+        This object may be used to read or update top and bottom widgets and
+        top widgets's options, but no widgets may be added or removed.
+
+        `top_options` takes the form
+        `(align_type, align_amount, width_type, width_amount, min_width, left,
+        right, valign_type, valign_amount, height_type, height_amount,
+        min_height, top, bottom)`
+
+        bottom_options is always
+        `('left', None, 'relative', 100, None, 0, 0,
+        'top', None, 'relative', 100, None, 0, 0)`
+        which means that bottom widget always covers the full area of the Overlay.
+        writing a different value for `bottom_options` raises an
+        :exc:`OverlayError`.
+        """
+
+        # noinspection PyMethodParameters
+        class OverlayContents(
+            MutableSequence[
+                tuple[
+                    typing.Union[TopWidget, BottomWidget],
+                    OverlayOptions,
+                ]
+            ]
+        ):
+            # pylint: disable=no-self-argument
+            def __len__(inner_self) -> int:
+                return 2
+
+            __getitem__ = self._contents__getitem__
+            __setitem__ = self._contents__setitem__
+
+            def __delitem__(self, index: int | slice) -> typing.NoReturn:
+                raise TypeError("OverlayContents is fixed-sized sequence")
+
+            def insert(self, index: int | slice, value: typing.Any) -> typing.NoReturn:
+                raise TypeError("OverlayContents is fixed-sized sequence")
+
+            def __repr__(inner_self) -> str:
+                return repr(f"<{inner_self.__class__.__name__}({[inner_self[0], inner_self[1]]})> for {self}")
+
+            def __rich_repr__(inner_self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+                for val in inner_self:
+                    yield None, val
+
+            def __iter__(inner_self) -> Iterator[tuple[Widget, OverlayOptions]]:
+                for idx in range(2):
+                    yield inner_self[idx]
+
+        return OverlayContents()
+
+    @contents.setter
+    def contents(self, new_contents: Sequence[tuple[width, OverlayOptions]]) -> None:
+        if len(new_contents) != 2:
+            raise ValueError("Contents length for overlay should be only 2")
+        self.contents[0] = new_contents[0]
+        self.contents[1] = new_contents[1]
+
+    def _contents__getitem__(
+        self,
+        index: Literal[0, 1],
+    ) -> tuple[TopWidget | BottomWidget, OverlayOptions]:
+        if index == 0:
+            return (self.bottom_w, self._DEFAULT_BOTTOM_OPTIONS)
+
+        if index == 1:
+            return (
+                self.top_w,
+                OverlayOptions(
+                    self.align_type,
+                    self.align_amount,
+                    self.width_type,
+                    self.width_amount,
+                    self.min_width,
+                    self.left,
+                    self.right,
+                    self.valign_type,
+                    self.valign_amount,
+                    self.height_type,
+                    self.height_amount,
+                    self.min_height,
+                    self.top,
+                    self.bottom,
+                ),
+            )
+        raise IndexError(f"Overlay.contents has no position {index!r}")
+
+    def _contents__setitem__(
+        self,
+        index: Literal[0, 1],
+        value: tuple[TopWidget | BottomWidget, OverlayOptions],
+    ) -> None:
+        try:
+            value_w, value_options = value
+        except (ValueError, TypeError) as exc:
+            raise OverlayError(f"added content invalid: {value!r}").with_traceback(exc.__traceback__) from exc
+        if index == 0:
+            if value_options != self._DEFAULT_BOTTOM_OPTIONS:
+                raise OverlayError(f"bottom_options must be set to {self._DEFAULT_BOTTOM_OPTIONS!r}")
+            self.bottom_w = value_w
+        elif index == 1:
+            try:
+                (
+                    align_type,
+                    align_amount,
+                    width_type,
+                    width_amount,
+                    min_width,
+                    left,
+                    right,
+                    valign_type,
+                    valign_amount,
+                    height_type,
+                    height_amount,
+                    min_height,
+                    top,
+                    bottom,
+                ) = value_options
+            except (ValueError, TypeError) as exc:
+                raise OverlayError(f"top_options is invalid: {value_options!r}").with_traceback(
+                    exc.__traceback__
+                ) from exc
+            # normalize first, this is where errors are raised
+            align_type, align_amount = normalize_align(simplify_align(align_type, align_amount), OverlayError)
+            width_type, width_amount = normalize_width(simplify_width(width_type, width_amount), OverlayError)
+            valign_type, valign_amount = normalize_valign(simplify_valign(valign_type, valign_amount), OverlayError)
+            height_type, height_amount = normalize_height(simplify_height(height_type, height_amount), OverlayError)
+            self.align_type = align_type
+            self.align_amount = align_amount
+            self.width_type = width_type
+            self.width_amount = width_amount
+            self.valign_type = valign_type
+            self.valign_amount = valign_amount
+            self.height_type = height_type
+            self.height_amount = height_amount
+            self.left = left
+            self.right = right
+            self.top = top
+            self.bottom = bottom
+            self.min_width = min_width
+            self.min_height = min_height
+        else:
+            raise IndexError(f"Overlay.contents has no position {index!r}")
+        self._invalidate()
+
+    def get_cursor_coords(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+    ) -> tuple[int, int] | None:
+        """Return cursor coords from top_w, if any."""
+        if not hasattr(self.top_w, "get_cursor_coords"):
+            return None
+        real_size = self.pack(size, True)
+        (maxcol, maxrow) = real_size
+        left, right, top, bottom = self.calculate_padding_filler(real_size, True)
+        x, y = self.top_w.get_cursor_coords((maxcol - left - right, maxrow - top - bottom))
+        if y >= maxrow:  # required??
+            y = maxrow - 1
+        return x + left, y + top
+
+    def calculate_padding_filler(
+        self,
+        size: tuple[int, int],
+        focus: bool,
+    ) -> tuple[int, int, int, int]:
+        """Return (padding left, right, filler top, bottom)."""
+        (maxcol, maxrow) = size
+        height = None
+        if self.width_type == WHSettings.PACK:
+            width, height = self.top_w.pack((), focus=focus)
+            if not height:
+                raise OverlayError("fixed widget must have a height")
+            left, right = calculate_left_right_padding(
+                maxcol,
+                self.align_type,
+                self.align_amount,
+                WrapMode.CLIP,
+                width,
+                None,
+                self.left,
+                self.right,
+            )
+        else:
+            left, right = calculate_left_right_padding(
+                maxcol,
+                self.align_type,
+                self.align_amount,
+                self.width_type,
+                self.width_amount,
+                self.min_width,
+                self.left,
+                self.right,
+            )
+
+        if height:
+            # top_w is a fixed widget
+            top, bottom = calculate_top_bottom_filler(
+                maxrow,
+                self.valign_type,
+                self.valign_amount,
+                WHSettings.GIVEN,
+                height,
+                None,
+                self.top,
+                self.bottom,
+            )
+            if maxrow - top - bottom < height:
+                bottom = maxrow - top - height
+        elif self.height_type == WHSettings.PACK:
+            # top_w is a flow widget
+            height = self.top_w.rows((maxcol,), focus=focus)
+            top, bottom = calculate_top_bottom_filler(
+                maxrow,
+                self.valign_type,
+                self.valign_amount,
+                WHSettings.GIVEN,
+                height,
+                None,
+                self.top,
+                self.bottom,
+            )
+            if height > maxrow:  # flow widget rendered too large
+                bottom = maxrow - height
+        else:
+            top, bottom = calculate_top_bottom_filler(
+                maxrow,
+                self.valign_type,
+                self.valign_amount,
+                self.height_type,
+                self.height_amount,
+                self.min_height,
+                self.top,
+                self.bottom,
+            )
+        return left, right, top, bottom
+
+    def top_w_size(
+        self,
+        size: tuple[int, int],
+        left: int,
+        right: int,
+        top: int,
+        bottom: int,
+    ) -> tuple[()] | tuple[int] | tuple[int, int]:
+        """Return the size to pass to top_w."""
+        if self.width_type == WHSettings.PACK:
+            # top_w is a fixed widget
+            return ()
+        maxcol, maxrow = size
+        if self.width_type != WHSettings.PACK and self.height_type == WHSettings.PACK:
+            # top_w is a flow widget
+            return (maxcol - left - right,)
+        return (maxcol - left - right, maxrow - top - bottom)
+
+    def render(self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False) -> CompositeCanvas:
+        """Render top_w overlayed on bottom_w."""
+        real_size = self.pack(size, focus)
+
+        left, right, top, bottom = self.calculate_padding_filler(real_size, focus)
+        bottom_c = self.bottom_w.render(real_size)
+        if not bottom_c.cols() or not bottom_c.rows():
+            return CompositeCanvas(bottom_c)
+
+        top_c = self.top_w.render(self.top_w_size(real_size, left, right, top, bottom), focus)
+        top_c = CompositeCanvas(top_c)
+        if left < 0 or right < 0:
+            top_c.pad_trim_left_right(min(0, left), min(0, right))
+        if top < 0 or bottom < 0:
+            top_c.pad_trim_top_bottom(min(0, top), min(0, bottom))
+
+        return CanvasOverlay(top_c, bottom_c, left, top)
+
+    def mouse_event(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """Pass event to top_w, ignore if outside of top_w."""
+        if not hasattr(self.top_w, "mouse_event"):
+            return False
+
+        real_size = self.pack(size, focus)
+
+        left, right, top, bottom = self.calculate_padding_filler(real_size, focus)
+        maxcol, maxrow = real_size
+        if col < left or col >= maxcol - right or row < top or row >= maxrow - bottom:
+            return False
+
+        return self.top_w.mouse_event(
+            self.top_w_size(real_size, left, right, top, bottom),
+            event,
+            button,
+            col - left,
+            row - top,
+            focus,
+        )
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/padding.py b/python/user_packages/Python313/site-packages/urwid/widget/padding.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3c2be0bf51e0cb86c7e765960a6f5f92d7ba764
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/padding.py
@@ -0,0 +1,575 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from urwid.canvas import CompositeCanvas, SolidCanvas
+from urwid.split_repr import remove_defaults
+from urwid.util import int_scale
+
+from .constants import (
+    RELATIVE_100,
+    Align,
+    Sizing,
+    WHSettings,
+    normalize_align,
+    normalize_width,
+    simplify_align,
+    simplify_width,
+)
+from .widget_decoration import WidgetDecoration, WidgetError, WidgetWarning
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterator
+
+    from typing_extensions import Literal
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class PaddingError(WidgetError):
+    """Padding related errors."""
+
+
+class PaddingWarning(WidgetWarning):
+    """Padding related warnings."""
+
+
+class Padding(WidgetDecoration[WrappedWidget], typing.Generic[WrappedWidget]):
+    def __init__(
+        self,
+        w: WrappedWidget,
+        align: (
+            Literal["left", "center", "right"]
+            | Align
+            | tuple[Literal["relative", WHSettings.RELATIVE, "fixed left", "fixed right"], int]
+        ) = Align.LEFT,
+        width: (
+            int
+            | Literal["pack", "clip", WHSettings.PACK, WHSettings.CLIP]
+            | tuple[Literal["relative", WHSettings.RELATIVE, "fixed left", "fixed right"], int]
+        ) = RELATIVE_100,
+        min_width: int | None = None,
+        left: int = 0,
+        right: int = 0,
+    ) -> None:
+        """
+        :param w: a box, flow or fixed widget to pad on the left and/or right
+            this widget is stored as self.original_widget
+        :type w: Widget
+
+        :param align: one of: ``'left'``, ``'center'``, ``'right'``
+            (``'relative'``, *percentage* 0=left 100=right)
+
+        :param width: one of:
+
+            *given width*
+              integer number of columns for self.original_widget
+
+            ``'pack'``
+              try to pack self.original_widget to its ideal size
+
+            (``'relative'``, *percentage of total width*)
+              make width depend on the container's width
+
+            ``'clip'``
+              to enable clipping mode for a fixed widget
+
+        :param min_width: the minimum number of columns for
+            self.original_widget or ``None``
+        :type min_width: int | None
+
+        :param left: a fixed number of columns to pad on the left
+        :type left: int
+
+        :param right: a fixed number of columns to pad on the right
+        :type right: int
+
+        Clipping Mode: (width= ``'clip'``)
+        In clipping mode this padding widget will behave as a flow
+        widget and self.original_widget will be treated as a fixed widget.
+        self.original_widget will be clipped to fit the available number of columns.
+        For example if align is ``'left'`` then self.original_widget may be clipped on the right.
+
+        Pack Mode: (width= ``'pack'``)
+        In pack mode is supported FIXED operation if it is supported by the original widget.
+
+        >>> from urwid import Divider, Text, BigText, FontRegistry
+        >>> from urwid.util import set_temporary_encoding
+        >>> size = (7,)
+        >>> def pr(w):
+        ...     with set_temporary_encoding("utf-8"):
+        ...         for t in w.render(size).text:
+        ...             print(f"|{t.decode('utf-8')}|")
+        >>> pr(Padding(Text("Head"), ("relative", 20), "pack"))
+        | Head  |
+        >>> pr(Padding(Divider("-"), left=2, right=1))
+        |  ---- |
+        >>> pr(Padding(Divider("*"), "center", 3))
+        |  ***  |
+        >>> p = Padding(Text("1234"), "left", 2, None, 1, 1)
+        >>> p
+         left=1 right=1 width=2>
+        >>> pr(p)  # align against left
+        | 12    |
+        | 34    |
+        >>> p.align = "right"
+        >>> pr(p)  # align against right
+        |    12 |
+        |    34 |
+        >>> pr(Padding(Text("hi\\nthere"), "right", "pack"))  # pack text first
+        |  hi   |
+        |  there|
+        >>> pr(Padding(BigText("1,2,3", FontRegistry["Thin 3x3"]()), width="clip"))
+        | ┐  ┌─┐|
+        | │  ┌─┘|
+        | ┴ ,└─ |
+        """
+        super().__init__(w)
+
+        # convert obsolete parameters 'fixed left' and 'fixed right':
+        if isinstance(align, tuple) and align[0] in {"fixed left", "fixed right"}:
+            if align[0] == "fixed left":
+                left = align[1]
+                align = Align.LEFT
+            else:
+                right = align[1]
+                align = Align.RIGHT
+        if isinstance(width, tuple) and width[0] in {"fixed left", "fixed right"}:
+            if width[0] == "fixed left":
+                left = width[1]
+            else:
+                right = width[1]
+            width = RELATIVE_100
+
+        # convert old clipping mode width=None to width='clip'
+        if width is None:
+            width = WHSettings.CLIP
+
+        self.left = left
+        self.right = right
+        self._align_type, self._align_amount = normalize_align(align, PaddingError)
+        self._width_type, self._width_amount = normalize_width(width, PaddingError)
+        self.min_width = min_width
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Widget sizing.
+
+        Rules:
+        * width == CLIP: only FLOW is supported, and wrapped widget should support FIXED
+        * width == GIVEN: FIXED is supported, and wrapped widget should support FLOW
+        * All other cases: use sizing of target widget
+        """
+        if self._width_type == WHSettings.CLIP:
+            return frozenset((Sizing.FLOW,))
+
+        sizing = set(self.original_widget.sizing())
+        if self._width_type == WHSettings.GIVEN:
+            if Sizing.FLOW in sizing:
+                sizing.add(Sizing.FIXED)
+
+            elif Sizing.BOX not in sizing:
+                warnings.warn(
+                    f"WHSettings.GIVEN expect BOX or FLOW widget to be used, but received {self.original_widget}",
+                    PaddingWarning,
+                    stacklevel=3,
+                )
+
+        return frozenset(sizing)
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "align": self.align,
+            "width": self.width,
+            "left": self.left,
+            "right": self.right,
+            "min_width": self.min_width,
+        }
+        return remove_defaults(attrs, Padding.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        yield "w", self.original_widget
+        yield "align", self.align
+        yield "width", self.width
+        yield "min_width", self.min_width
+        yield "left", self.left
+        yield "right", self.right
+
+    @property
+    def align(
+        self,
+    ) -> Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int]:
+        """
+        Return the padding alignment setting.
+        """
+        return simplify_align(self._align_type, self._align_amount)
+
+    @align.setter
+    def align(
+        self, align: Literal["left", "center", "right"] | Align | tuple[Literal["relative", WHSettings.RELATIVE], int]
+    ) -> None:
+        """
+        Set the padding alignment.
+        """
+        self._align_type, self._align_amount = normalize_align(align, PaddingError)
+        self._invalidate()
+
+    @property
+    def width(
+        self,
+    ) -> (
+        Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK]
+        | int
+        | tuple[Literal["relative", WHSettings.RELATIVE], int]
+    ):
+        """
+        Return the padding width.
+        """
+        return simplify_width(self._width_type, self._width_amount)
+
+    @width.setter
+    def width(
+        self,
+        width: (
+            Literal["clip", "pack", WHSettings.CLIP, WHSettings.PACK]
+            | int
+            | tuple[Literal["relative", WHSettings.RELATIVE], int]
+        ),
+    ) -> None:
+        """
+        Set the padding width.
+        """
+        self._width_type, self._width_amount = normalize_width(width, PaddingError)
+        self._invalidate()
+
+    def pack(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int] = (),
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        if size:
+            return super().pack(size, focus)
+        if self._width_type == WHSettings.CLIP:
+            raise PaddingError("WHSettings.CLIP makes Padding FLOW-only widget")
+
+        expand = self.left + self.right
+        w_sizing = self.original_widget.sizing()
+
+        if self._width_type == WHSettings.GIVEN:
+            if Sizing.FLOW not in w_sizing:
+                warnings.warn(
+                    f"WHSettings.GIVEN expect FLOW widget to be used for FIXED pack/render, "
+                    f"but received {self.original_widget}",
+                    PaddingWarning,
+                    stacklevel=3,
+                )
+
+            return (
+                max(self._width_amount, self.min_width or 1) + expand,
+                self.original_widget.rows((self._width_amount,), focus),
+            )
+
+        if Sizing.FIXED not in w_sizing:
+            warnings.warn(
+                f"Padded widget should support FIXED sizing for FIXED render, but received {self.original_widget}",
+                PaddingWarning,
+                stacklevel=3,
+            )
+        width, height = self.original_widget.pack(size, focus)
+
+        if self._width_type == WHSettings.PACK:
+            return max(width, self.min_width or 1) + expand, height
+
+        if self._width_type == WHSettings.RELATIVE:
+            return max(int(width * 100 / self._width_amount + 0.5), self.min_width or 1) + expand, height
+
+        raise PaddingError(f"Unexpected width type: {self._width_type.upper()})")
+
+    def render(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        left, right = self.padding_values(size, focus)
+
+        if self._width_type == WHSettings.CLIP:
+            canv = self._original_widget.render((), focus)
+        elif size:
+            maxcol = size[0] - (left + right)
+            if self._width_type == WHSettings.GIVEN and maxcol < self._width_amount:
+                warnings.warn(
+                    f"{self}.render(size={size}, focus={focus}): too narrow size ({maxcol!r} < {self._width_amount!r})",
+                    PaddingWarning,
+                    stacklevel=3,
+                )
+            canv = self._original_widget.render((maxcol, *size[1:]), focus)
+        elif self._width_type == WHSettings.GIVEN:
+            canv = self._original_widget.render((self._width_amount, *size[1:]), focus)
+        else:
+            canv = self._original_widget.render((), focus)
+
+        if canv.cols() == 0:
+            canv = SolidCanvas(" ", size[0], canv.rows())
+            canv = CompositeCanvas(canv)
+            canv.set_depends([self._original_widget])
+            return canv
+
+        canv = CompositeCanvas(canv)
+        canv.set_depends([self._original_widget])
+        if left != 0 or right != 0:
+            canv.pad_trim_left_right(left, right)
+
+        return canv
+
+    def padding_values(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        focus: bool,
+    ) -> tuple[int, int]:
+        """Return the number of columns to pad on the left and right.
+
+        Override this method to define custom padding behaviour."""
+        if self._width_type == WHSettings.CLIP:
+            width, _ignore = self._original_widget.pack((), focus=focus)
+            if not size:
+                raise PaddingError("WHSettings.CLIP makes Padding FLOW-only widget")
+            return calculate_left_right_padding(
+                size[0],
+                self._align_type,
+                self._align_amount,
+                WHSettings.CLIP,
+                width,
+                None,
+                self.left,
+                self.right,
+            )
+
+        if self._width_type == WHSettings.PACK:
+            if size:
+                maxcol = size[0]
+                maxwidth = max(maxcol - self.left - self.right, self.min_width or 0)
+                (width, _ignore) = self._original_widget.pack((maxwidth,), focus=focus)
+            else:
+                (width, _ignore) = self._original_widget.pack((), focus=focus)
+                maxcol = width + self.left + self.right
+
+            return calculate_left_right_padding(
+                maxcol,
+                self._align_type,
+                self._align_amount,
+                WHSettings.GIVEN,
+                width,
+                self.min_width,
+                self.left,
+                self.right,
+            )
+
+        if size:
+            maxcol = size[0]
+        elif self._width_type == WHSettings.GIVEN:
+            maxcol = self._width_amount + self.left + self.right
+        else:
+            maxcol = (
+                max(self._original_widget.pack((), focus=focus)[0] * 100 // self._width_amount, self.min_width or 1)
+                + self.left
+                + self.right
+            )
+
+        return calculate_left_right_padding(
+            maxcol,
+            self._align_type,
+            self._align_amount,
+            self._width_type,
+            self._width_amount,
+            self.min_width,
+            self.left,
+            self.right,
+        )
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """Return the rows needed for self.original_widget."""
+        (maxcol,) = size
+        left, right = self.padding_values(size, focus)
+        if self._width_type == WHSettings.PACK:
+            _pcols, prows = self._original_widget.pack((maxcol - left - right,), focus)
+            return prows
+        if self._width_type == WHSettings.CLIP:
+            _fcols, frows = self._original_widget.pack((), focus)
+            return frows
+        return self._original_widget.rows((maxcol - left - right,), focus=focus)
+
+    def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None:
+        """Pass keypress to self._original_widget."""
+        left, right = self.padding_values(size, True)
+        if size:
+            maxvals = (size[0] - left - right, *size[1:])
+            return self._original_widget.keypress(maxvals, key)
+        return self._original_widget.keypress((), key)
+
+    def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None:
+        """Return the (x,y) coordinates of cursor within self._original_widget."""
+        if not hasattr(self._original_widget, "get_cursor_coords"):
+            return None
+
+        left, right = self.padding_values(size, True)
+        if size:
+            maxvals = (size[0] - left - right, *size[1:])
+            if maxvals[0] == 0:
+                return None
+        else:
+            maxvals = ()
+
+        if (coords := self._original_widget.get_cursor_coords(maxvals)) is not None:
+            x, y = coords
+            return x + left, y
+
+        return None
+
+    def move_cursor_to_coords(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        x: int,
+        y: int,
+    ) -> bool:
+        """Set the cursor position with (x,y) coordinates of self._original_widget.
+
+        Returns True if move succeeded, False otherwise.
+        """
+        if not hasattr(self._original_widget, "move_cursor_to_coords"):
+            return True
+
+        left, right = self.padding_values(size, True)
+        if size:
+            maxcol = size[0]
+            maxvals = (maxcol - left - right, *size[1:])
+        else:
+            maxcol = self.pack((), True)[0]
+            maxvals = ()
+
+        if isinstance(x, int):
+            if x < left:
+                x = left
+            elif x >= maxcol - right:
+                x = maxcol - right - 1
+            x -= left
+
+        return self._original_widget.move_cursor_to_coords(maxvals, x, y)
+
+    def mouse_event(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """Send mouse event if position is within self._original_widget."""
+        if not hasattr(self._original_widget, "mouse_event"):
+            return False
+
+        left, right = self.padding_values(size, focus)
+        if size:
+            maxcol = size[0]
+            if col < left or col >= maxcol - right:
+                return False
+            maxvals = (maxcol - left - right, *size[1:])
+        else:
+            maxvals = ()
+
+        return self._original_widget.mouse_event(maxvals, event, button, col - left, row, focus)
+
+    def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int | None:
+        """Return the preferred column from self._original_widget, or None."""
+        if not hasattr(self._original_widget, "get_pref_col"):
+            return None
+
+        left, right = self.padding_values(size, True)
+        if size:
+            maxvals = (size[0] - left - right, *size[1:])
+        else:
+            maxvals = ()
+
+        x = self._original_widget.get_pref_col(maxvals)
+        if isinstance(x, int):
+            return x + left
+        return x
+
+
+def calculate_left_right_padding(
+    maxcol: int,
+    align_type: Literal["left", "center", "right"] | Align,
+    align_amount: int,
+    width_type: Literal["fixed", "relative", "clip", "given", WHSettings.RELATIVE, WHSettings.CLIP, WHSettings.GIVEN],
+    width_amount: int,
+    min_width: int | None,
+    left: int,
+    right: int,
+) -> tuple[int, int]:
+    """
+    Return the amount of padding (or clipping) on the left and
+    right part of maxcol columns to satisfy the following:
+
+    align_type -- 'left', 'center', 'right', 'relative'
+    align_amount -- a percentage when align_type=='relative'
+    width_type -- 'fixed', 'relative', 'clip'
+    width_amount -- a percentage when width_type=='relative'
+        otherwise equal to the width of the widget
+    min_width -- a desired minimum width for the widget or None
+    left -- a fixed number of columns to pad on the left
+    right -- a fixed number of columns to pad on the right
+
+    >>> clrp = calculate_left_right_padding
+    >>> clrp(15, "left", 0, "given", 10, None, 2, 0)
+    (2, 3)
+    >>> clrp(15, "relative", 0, "given", 10, None, 2, 0)
+    (2, 3)
+    >>> clrp(15, "relative", 100, "given", 10, None, 2, 0)
+    (5, 0)
+    >>> clrp(15, "center", 0, "given", 4, None, 2, 0)
+    (6, 5)
+    >>> clrp(15, "left", 0, "clip", 18, None, 0, 0)
+    (0, -3)
+    >>> clrp(15, "right", 0, "clip", 18, None, 0, -1)
+    (-2, -1)
+    >>> clrp(15, "center", 0, "given", 18, None, 2, 0)
+    (0, 0)
+    >>> clrp(20, "left", 0, "relative", 60, None, 0, 0)
+    (0, 8)
+    >>> clrp(20, "relative", 30, "relative", 60, None, 0, 0)
+    (2, 6)
+    >>> clrp(20, "relative", 30, "relative", 60, 14, 0, 0)
+    (2, 4)
+    """
+    if width_type == WHSettings.RELATIVE:
+        maxwidth = max(maxcol - left - right, 0)
+        width = int(maxwidth * width_amount / 100 + 0.5)
+        if min_width is not None:
+            width = max(width, min_width)
+    else:
+        width = width_amount
+
+    align = {Align.LEFT: 0, Align.CENTER: 50, Align.RIGHT: 100}.get(align_type, align_amount)
+
+    # add the remainder of left/right the padding
+    padding = maxcol - width - left - right
+    right += int_scale(100 - align, 101, padding + 1)
+    left = maxcol - width - right
+
+    # reduce padding if we are clipping an edge
+    if right < 0 < left:
+        shift = min(left, -right)
+        left -= shift
+        right += shift
+    elif left < 0 < right:
+        shift = min(right, -left)
+        right -= shift
+        left += shift
+
+    # only clip if width_type == 'clip'
+    if width_type != WHSettings.CLIP and (left < 0 or right < 0):
+        left = max(left, 0)
+        right = max(right, 0)
+
+    return left, right
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/pile.py b/python/user_packages/Python313/site-packages/urwid/widget/pile.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1537d08c64c477f9d9ca1592b91f0427b9846f1
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/pile.py
@@ -0,0 +1,1049 @@
+from __future__ import annotations
+
+import typing
+import warnings
+from itertools import chain, repeat
+
+from urwid.canvas import CanvasCombine, CompositeCanvas, SolidCanvas
+from urwid.command_map import Command
+from urwid.split_repr import remove_defaults
+from urwid.util import is_mouse_press
+
+from .constants import Sizing, WHSettings
+from .container import WidgetContainerListContentsMixin, WidgetContainerMixin, _ContainerElementSizingFlag
+from .monitored_list import MonitoredFocusList, MonitoredList
+from .widget import Widget, WidgetError, WidgetWarning
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterable, Iterator, Sequence
+
+    from typing_extensions import Literal
+
+
+class PileError(WidgetError):
+    """Pile related errors."""
+
+
+class PileWarning(WidgetWarning):
+    """Pile related warnings."""
+
+
+class Pile(Widget, WidgetContainerMixin, WidgetContainerListContentsMixin):
+    """
+    A pile of widgets stacked vertically from top to bottom
+    """
+
+    def sizing(self) -> frozenset[Sizing]:
+        """Sizing supported by widget.
+
+        :return: Calculated widget sizing
+        :rtype: frozenset[Sizing]
+
+        Due to the nature of container with mutable contents, this method cannot be cached.
+
+        Rules:
+        * WEIGHT BOX -> BOX
+        * GIVEN BOX -> FLOW (height is known) & BOX (can be shrinked/padded)
+        * PACK BOX -> Unsupported
+
+        * WEIGHT FLOW -> FLOW
+        * GIVEN FLOW -> Unsupported
+        * PACK FLOW -> FLOW
+
+        * WEIGHT FIXED -> Need also FLOW or/and BOX to properly render due to width calculation
+        * GIVEN FIXED -> Unsupported
+        * PACK FIXED -> FIXED (widget knows its size)
+
+        >>> from urwid import BigText, ProgressBar, SolidFill, Text, Thin3x3Font
+        >>> font = Thin3x3Font()
+
+        # BOX-only widget
+        >>> Pile((SolidFill("#"),))
+        
+
+        # GIVEN BOX -> BOX/FLOW
+        >>> Pile(((10, SolidFill("#")),))
+        
+
+        # FLOW-only
+        >>> Pile((ProgressBar(None, None),))
+        
+
+        # FIXED -> FIXED
+        >>> Pile(((WHSettings.PACK, BigText("0", font)),))
+        
+
+        # FLOW/FIXED -> FLOW/FIXED
+        >>> Pile(((WHSettings.PACK, Text("text")),))
+        
+
+        # FLOW + FIXED widgets -> FLOW/FIXED
+        >>> Pile((ProgressBar(None, None), (WHSettings.PACK, BigText("0", font))))
+        
+
+        # GIVEN BOX + FIXED widgets -> BOX/FLOW/FIXED (GIVEN BOX allows overriding its height & allows any width)
+        >>> Pile(((10, SolidFill("#")), (WHSettings.PACK, BigText("0", font))))
+        
+
+        # Invalid sizing combination -> use fallback settings (and produce warning)
+        >>> Pile(((WHSettings.WEIGHT, 1, BigText("0", font)),))
+        
+
+        # Special case: empty pile widget sizing is impossible to calculate
+        >>> Pile(())
+        
+        """
+        if not self.contents:
+            return frozenset((Sizing.BOX, Sizing.FLOW))
+        strict_box = False
+        has_flow = False
+
+        has_fixed = False
+        supported: set[Sizing] = set()
+
+        box_flow_fixed = (
+            _ContainerElementSizingFlag.BOX | _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED
+        )
+        flow_fixed = _ContainerElementSizingFlag.FLOW | _ContainerElementSizingFlag.FIXED
+
+        for idx, (widget, (size_kind, _size_weight)) in enumerate(self.contents):
+            w_sizing = widget.sizing()
+
+            flag = _ContainerElementSizingFlag.NONE
+
+            if size_kind == WHSettings.WEIGHT:
+                flag |= _ContainerElementSizingFlag.WH_WEIGHT
+                if Sizing.BOX in w_sizing:
+                    flag |= _ContainerElementSizingFlag.BOX
+                if Sizing.FLOW in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FLOW
+                if Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}:
+                    flag |= _ContainerElementSizingFlag.FIXED
+
+            elif size_kind == WHSettings.GIVEN:
+                flag |= _ContainerElementSizingFlag.WH_GIVEN
+                if Sizing.BOX in w_sizing:
+                    flag |= _ContainerElementSizingFlag.BOX
+                    flag |= _ContainerElementSizingFlag.FLOW
+
+            else:
+                flag = _ContainerElementSizingFlag.WH_PACK
+                if Sizing.FLOW in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FLOW
+                if Sizing.FIXED in w_sizing:
+                    flag |= _ContainerElementSizingFlag.FIXED
+
+            if not flag & box_flow_fixed:
+                warnings.warn(
+                    f"Sizing combination of widget {idx} not supported: {size_kind.name} {'|'.join(w_sizing).upper()}",
+                    PileWarning,
+                    stacklevel=3,
+                )
+                return frozenset((Sizing.BOX, Sizing.FLOW))
+
+            if flag & _ContainerElementSizingFlag.BOX:
+                supported.add(Sizing.BOX)
+                if not flag & flow_fixed:
+                    strict_box = True
+                    break
+
+            if flag & _ContainerElementSizingFlag.FLOW:
+                has_flow = True
+            if flag & _ContainerElementSizingFlag.FIXED:
+                has_fixed = True
+
+        if not strict_box:
+            if has_flow:
+                supported.add(Sizing.FLOW)
+            if has_fixed:
+                supported.add(Sizing.FIXED)
+
+        return frozenset(supported)
+
+    def __init__(
+        self,
+        widget_list: Iterable[
+            Widget
+            | tuple[Literal["pack", WHSettings.PACK] | int, Widget]
+            | tuple[Literal["given", WHSettings.GIVEN], int, Widget]
+            | tuple[Literal["weight", WHSettings.WEIGHT], int | float, Widget]
+        ],
+        focus_item: Widget | int | None = None,
+    ) -> None:
+        """
+        :param widget_list: child widgets
+        :type widget_list: iterable
+        :param focus_item: child widget that gets the focus initially.
+            Chooses the first selectable widget if unset.
+        :type focus_item: Widget or int
+
+        *widget_list* may also contain tuples such as:
+
+        (*given_height*, *widget*)
+            always treat *widget* as a box widget and give it *given_height* rows, where given_height is an int
+        (``'pack'``, *widget*)
+            allow *widget* to calculate its own height by calling its :meth:`rows` method,
+            i.e. treat it as a flow widget.
+        (``'weight'``, *weight*, *widget*)
+            if the pile is treated as a box widget then treat widget as a box
+            widget with a height based on its relative weight value, otherwise treat the same as (``'pack'``, *widget*).
+
+        Widgets not in a tuple are the same as (``'weight'``, ``1``, *widget*)`
+
+        .. note:: If the Pile is treated as a box widget there must be at least
+            one ``'weight'`` tuple in :attr:`widget_list`.
+        """
+        self._selectable = False
+        super().__init__()
+        self._contents: MonitoredFocusList[
+            Widget,
+            tuple[Literal[WHSettings.PACK], None]
+            | tuple[Literal[WHSettings.GIVEN], int]
+            | tuple[Literal[WHSettings.WEIGHT], int | float],
+        ] = MonitoredFocusList()
+        self._contents.set_modified_callback(self._contents_modified)
+        self._contents.set_focus_changed_callback(lambda f: self._invalidate())
+        self._contents.set_validate_contents_modified(self._validate_contents_modified)
+
+        for i, original in enumerate(widget_list):
+            w = original
+            if not isinstance(w, tuple):
+                self.contents.append((w, (WHSettings.WEIGHT, 1)))
+            elif w[0] in {Sizing.FLOW, WHSettings.PACK}:  # 'pack' used to be called 'flow'
+                f, w = w
+                self.contents.append((w, (WHSettings.PACK, None)))
+            elif len(w) == 2 or w[0] in {Sizing.FIXED, WHSettings.GIVEN}:  # backwards compatibility
+                height, w = w[-2:]
+                self.contents.append((w, (WHSettings.GIVEN, height)))
+            elif w[0] == WHSettings.WEIGHT:
+                f, height, w = w
+                self.contents.append((w, (f, height)))
+            else:
+                raise PileError(f"initial widget list item invalid {original!r}")
+            if focus_item is None and w.selectable():
+                focus_item = i
+
+            if not isinstance(w, Widget):
+                warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3)
+
+        if self.contents and focus_item is not None:
+            self.focus = focus_item
+
+        self.pref_col = 0
+
+    def _repr_words(self) -> list[str]:
+        if len(self.contents) > 1:
+            contents_string = f"({len(self.contents)} items)"
+        elif self.contents:
+            contents_string = "(1 item)"
+        else:
+            contents_string = "()"
+        return [*super()._repr_words(), contents_string]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {**super()._repr_attrs(), "focus_item": self.focus_position if len(self._contents) > 1 else None}
+        return remove_defaults(attrs, Pile.__init__)
+
+    def __rich_repr__(self) -> Iterator[tuple[str | None, typing.Any] | typing.Any]:
+        widget_list: list[
+            Widget
+            | tuple[Literal[WHSettings.PACK] | int, Widget]
+            | tuple[Literal[WHSettings.WEIGHT], int | float, Widget]
+        ] = []
+
+        for w_instance, (sizing, amount) in self._contents:
+            if sizing == WHSettings.GIVEN:
+                widget_list.append((amount, w_instance))
+            elif sizing == WHSettings.PACK:
+                widget_list.append((WHSettings.PACK, w_instance))
+            elif sizing == WHSettings.WEIGHT:
+                if amount == 1:
+                    widget_list.append(w_instance)
+                else:
+                    widget_list.append((WHSettings.WEIGHT, amount, w_instance))
+
+        yield "widget_list", widget_list
+        yield "focus_item", self.focus_position if self._contents else None
+
+    def __len__(self) -> int:
+        return len(self._contents)
+
+    def _contents_modified(self) -> None:
+        """Recalculate whether this widget should be selectable whenever the contents has been changed."""
+        self._selectable = any(w.selectable() for w, o in self.contents)
+        self._invalidate()
+
+    def _validate_contents_modified(self, slc, new_items) -> None:
+        invalid_items: list[tuple[Widget, tuple[typing.Any, typing.Any]]] = []
+        try:
+            for item in new_items:
+                _w, (t, n) = item
+                if any(
+                    (
+                        t not in {WHSettings.PACK, WHSettings.GIVEN, WHSettings.WEIGHT},
+                        (n is not None and (not isinstance(n, (int, float)) or n < 0)),
+                    )
+                ):
+                    invalid_items.append(item)
+
+        except (TypeError, ValueError) as exc:
+            raise PileError(f"added content invalid: {exc}").with_traceback(exc.__traceback__) from exc
+
+        if invalid_items:
+            raise PileError(f"added content invalid: {invalid_items!r}")
+
+    @property
+    def widget_list(self):
+        """
+        A list of the widgets in this Pile
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`contents`.
+        """
+        warnings.warn(
+            "only for backwards compatibility. You should use the new standard container property `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(w for w, t in self.contents)
+
+        def user_modified():
+            self.widget_list = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @widget_list.setter
+    def widget_list(self, widgets):
+        focus_position = self.focus_position
+        self.contents = [
+            (new, options)
+            for (new, (w, options)) in zip(
+                widgets,
+                # need to grow contents list if widgets is longer
+                chain(self.contents, repeat((None, (WHSettings.WEIGHT, 1)))),
+            )
+        ]
+        if focus_position < len(widgets):
+            self.focus_position = focus_position
+
+    @property
+    def item_types(self):
+        """
+        A list of the options values for widgets in this Pile.
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`contents`.
+        """
+        warnings.warn(
+            "only for backwards compatibility. You should use the new standard container property `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        ml = MonitoredList(
+            # return the old item type names
+            ({WHSettings.GIVEN: Sizing.FIXED, WHSettings.PACK: Sizing.FLOW}.get(f, f), height)
+            for w, (f, height) in self.contents
+        )
+
+        def user_modified():
+            self.item_types = ml
+
+        ml.set_modified_callback(user_modified)
+        return ml
+
+    @item_types.setter
+    def item_types(self, item_types):
+        warnings.warn(
+            "only for backwards compatibility. You should use the new standard container property `contents`."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        focus_position = self.focus_position
+        self.contents = [
+            (w, ({Sizing.FIXED: WHSettings.GIVEN, Sizing.FLOW: WHSettings.PACK}.get(new_t, new_t), new_height))
+            for ((new_t, new_height), (w, options)) in zip(item_types, self.contents)
+        ]
+        if focus_position < len(item_types):
+            self.focus_position = focus_position
+
+    @property
+    def contents(
+        self,
+    ) -> MonitoredFocusList[
+        Widget,
+        tuple[Literal[WHSettings.PACK], None]
+        | tuple[Literal[WHSettings.GIVEN], int]
+        | tuple[Literal[WHSettings.WEIGHT], int | float],
+    ]:
+        """
+        The contents of this Pile as a list of (widget, options) tuples.
+
+        options currently may be one of
+
+        (``'pack'``, ``None``)
+            allow widget to calculate its own height by calling its
+            :meth:`rows ` method, i.e. treat it as a flow widget.
+        (``'given'``, *n*)
+            Always treat widget as a box widget with a given height of *n* rows.
+        (``'weight'``, *w*)
+            If the Pile itself is treated as a box widget then
+            the value *w* will be used as a relative weight for assigning rows
+            to this box widget. If the Pile is being treated as a flow
+            widget then this is the same as (``'pack'``, ``None``) and the *w*
+            value is ignored.
+
+        If the Pile itself is treated as a box widget then at least one
+        widget must have a (``'weight'``, *w*) options value, or the Pile will
+        not be able to grow to fill the required number of rows.
+
+        This list may be modified like a normal list and the Pile widget
+        will updated automatically.
+
+        .. seealso:: Create new options tuples with the :meth:`options` method
+        """
+        return self._contents
+
+    @contents.setter
+    def contents(
+        self,
+        c: Sequence[
+            Widget,
+            tuple[Literal[WHSettings.PACK], None]
+            | tuple[Literal[WHSettings.GIVEN], int]
+            | tuple[Literal[WHSettings.WEIGHT], int | float],
+        ],
+    ) -> None:
+        self._contents[:] = c
+
+    @staticmethod
+    def options(
+        height_type: Literal["pack", "given", "weight"] | WHSettings = WHSettings.WEIGHT,
+        height_amount: int | float | None = 1,  # noqa: PYI041  # provide explicit for IDEs
+    ) -> (
+        tuple[Literal[WHSettings.PACK], None]
+        | tuple[Literal[WHSettings.GIVEN], int]
+        | tuple[Literal[WHSettings.WEIGHT], int | float]
+    ):
+        """
+        Return a new options tuple for use in a Pile's :attr:`contents` list.
+
+        :param height_type: ``'pack'``, ``'given'`` or ``'weight'``
+        :param height_amount: ``None`` for ``'pack'``, a number of rows for
+            ``'fixed'`` or a weight value (number) for ``'weight'``
+        """
+
+        if height_type == WHSettings.PACK:
+            return (WHSettings.PACK, None)
+        if height_type in {WHSettings.GIVEN, WHSettings.WEIGHT} and height_amount is not None:
+            return (height_type, height_amount)
+        raise PileError(f"invalid combination: height_type={height_type!r}, height_amount={height_amount!r}")
+
+    @property
+    def focus(self) -> Widget | None:
+        """the child widget in focus or None when Pile is empty"""
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    @focus.setter
+    def focus(self, item: Widget | int) -> None:
+        """
+        Set the item in focus, for backwards compatibility.
+
+        .. note:: only for backwards compatibility. You should use the new
+            standard container property :attr:`focus_position`.
+            to set the position by integer index instead.
+
+        :param item: element to focus
+        :type item: Widget or int
+        """
+        if isinstance(item, int):
+            self.focus_position = item
+            return
+        for i, (w, _options) in enumerate(self.contents):
+            if item == w:
+                self.focus_position = i
+                return
+        raise ValueError(f"Widget not found in Pile contents: {item!r}")
+
+    def get_focus(self) -> Widget | None:
+        """
+        Return the widget in focus, for backwards compatibility.  You may
+        also use the new standard container property .focus to get the
+        child widget in focus.
+        """
+        warnings.warn(
+            "for backwards compatibility."
+            "You may also use the new standard container property .focus to get the child widget in focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if not self.contents:
+            return None
+        return self.contents[self.focus_position][0]
+
+    def set_focus(self, item: Widget | int) -> None:
+        warnings.warn(
+            "for backwards compatibility."
+            "You may also use the new standard container property .focus to get the child widget in focus."
+            "API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        if isinstance(item, int):
+            self.focus_position = item
+            return
+        for i, (w, _options) in enumerate(self.contents):
+            if item == w:
+                self.focus_position = i
+                return
+        raise ValueError(f"Widget not found in Pile contents: {item!r}")
+
+    @property
+    def focus_item(self):
+        warnings.warn(
+            "only for backwards compatibility."
+            "You should use the new standard container properties "
+            "`focus` and `focus_position` to get the child widget in focus or modify the focus position."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self.focus
+
+    @focus_item.setter
+    def focus_item(self, new_item):
+        warnings.warn(
+            "only for backwards compatibility."
+            "You should use the new standard container properties "
+            "`focus` and `focus_position` to get the child widget in focus or modify the focus position."
+            "API will be removed in version 4.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self.focus = new_item
+
+    @property
+    def focus_position(self) -> int:
+        """
+        index of child widget in focus.
+        Raises :exc:`IndexError` if read when Pile is empty, or when set to an invalid index.
+        """
+        if not self.contents:
+            raise IndexError("No focus_position, Pile is empty")
+        return self.contents.focus
+
+    @focus_position.setter
+    def focus_position(self, position: int) -> None:
+        """
+        Set the widget in focus.
+
+        position -- index of child widget to be made focus
+        """
+        try:
+            if position < 0 or position >= len(self.contents):
+                raise IndexError(f"No Pile child widget at position {position}")
+        except TypeError as exc:
+            raise IndexError(f"No Pile child widget at position {position}").with_traceback(exc.__traceback__) from exc
+        self.contents.focus = position
+
+    def get_pref_col(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> int | None:
+        """Return the preferred column for the cursor, or None."""
+        if not self.selectable():
+            return None
+
+        if not self.contents:
+            return None
+
+        _, _, size_args = self.get_rows_sizes(size, focus=self.selectable())
+        self._update_pref_col_from_focus(size_args[self.focus_position])
+        return self.pref_col
+
+    def get_item_size(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        i: int,
+        focus: bool,
+        item_rows: list[int] | None = None,
+    ) -> tuple[()] | tuple[int] | tuple[int, int]:
+        """
+        Return a size appropriate for passing to self.contents[i][0].render
+        """
+        warnings.warn(
+            "get_item_size is going to be deprecated and can be removed soon."
+            "This method is not used by the urwid codebase and `get_rows_sizes` is used for the similar purposes.",
+            PendingDeprecationWarning,
+            stacklevel=2,
+        )
+        _w, (f, height) = self.contents[i]
+        if f == WHSettings.PACK:
+            if not size:
+                return ()
+            return (size[0],)
+
+        if not size:
+            raise PileError(f"Element {i} using parameters {f} and do not have full size information")
+
+        maxcol = size[0]
+
+        if f == WHSettings.GIVEN:
+            return (maxcol, height)
+
+        if f == WHSettings.WEIGHT:
+            if len(size) == 2:
+                if not item_rows:
+                    item_rows = self.get_item_rows(size, focus)
+                return (maxcol, item_rows[i])
+
+            return (maxcol,)
+
+        raise PileError(f"Unsupported item height rules: {f}")
+
+    def _get_fixed_rows_sizes(
+        self,
+        focus: bool = False,
+    ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int] | tuple[()]]]:
+        """Get rows widths, heights and render size parameters
+
+        Fixed case expect widget sizes calculation with several cycles for unknown height cases.
+        """
+        if not self.contents:
+            return (), (), ()
+
+        widths: dict[int, int] = {}
+        heights: dict[int, int] = {}
+        w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {}
+
+        flow: list[tuple[Widget, int, bool]] = []
+        box: list[int] = []
+        weighted: dict[int, list[int]] = {}
+        weights: list[int] = []
+        weight_max_sizes: dict[int, int] = {}
+
+        for idx, (widget, (size_kind, size_weight)) in enumerate(self.contents):
+            w_sizing = widget.sizing()
+            focused = focus and self.focus == widget
+            if size_kind == WHSettings.PACK:
+                if Sizing.FIXED in w_sizing:
+                    widths[idx], heights[idx] = widget.pack((), focused)
+                    w_h_args[idx] = ()
+                if Sizing.FLOW in w_sizing:
+                    # re-calculate height at the end
+                    flow.append((widget, idx, focused))
+                if not w_sizing & {Sizing.FIXED, Sizing.FLOW}:
+                    raise PileError(f"Unsupported sizing {w_sizing} for {size_kind.upper()}")
+
+            elif size_kind == WHSettings.GIVEN:
+                heights[idx] = size_weight
+                if Sizing.BOX in w_sizing:
+                    box.append(idx)
+                else:
+                    raise PileError(f"Unsupported sizing {w_sizing} for {size_kind.upper()}")
+
+            elif size_weight <= 0:
+                widths[idx] = 0
+                heights[idx] = 0
+                if Sizing.FLOW in w_sizing:
+                    w_h_args[idx] = (0,)
+                else:
+                    w_sizing[idx] = (0, 0)
+
+            elif Sizing.FIXED in w_sizing and w_sizing & {Sizing.BOX, Sizing.FLOW}:
+                width, height = widget.pack((), focused)
+                widths[idx] = width  # We're fitting everything in case of FIXED
+
+                if Sizing.BOX in w_sizing:
+                    weighted.setdefault(size_weight, []).append(idx)
+                    weights.append(size_weight)
+
+                    weight_max_sizes.setdefault(size_weight, height)
+                    weight_max_sizes[size_weight] = max(weight_max_sizes[size_weight], height)
+
+                else:
+                    # width replace is allowed
+                    flow.append((widget, idx, focused))
+
+            elif Sizing.FLOW in w_sizing:
+                # FLOW WEIGHT widgets are rendered the same as PACK WEIGHT
+                flow.append((widget, idx, focused))
+            else:
+                raise PileError(f"Unsupported combination of {size_kind}, {w_sizing}")
+
+        if not widths:
+            raise PileError("No widgets providing width information")
+
+        max_width = max(widths.values())
+
+        for widget, idx, focused in flow:
+            widths[idx] = max_width
+            heights[idx] = widget.rows((max_width,), focused)
+            w_h_args[idx] = (max_width,)
+
+        if weight_max_sizes:
+            max_weighted_coefficient = max(height / weight for weight, height in weight_max_sizes.items())
+
+            for weight in weight_max_sizes:
+                height = max(int(max_weighted_coefficient * weight + 0.5), 1)
+                for idx in weighted[weight]:
+                    heights[idx] = height
+                    w_h_args[idx] = (max_width, height)
+
+        for idx in box:
+            widths[idx] = max_width
+            w_h_args[idx] = (max_width, heights[idx])
+
+        return (
+            tuple(widths[idx] for idx in range(len(widths))),
+            tuple(heights[idx] for idx in range(len(heights))),
+            tuple(w_h_args[idx] for idx in range(len(w_h_args))),
+        )
+
+    def _get_flow_rows_sizes(
+        self,
+        size: tuple[int],
+        focus: bool = False,
+    ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int] | tuple[()]]]:
+        """Get rows widths, heights and render size parameters
+
+        Flow case is the simplest one: minimum cycles in the logic and no widgets manipulation.
+        Here we can make some shortcuts
+        """
+        maxcol = size[0]
+        if not self.contents:
+            return (maxcol,), (0,), ()
+
+        widths: Sequence[int] = (maxcol,) * len(self.contents)
+        heights: list[int] = []
+        w_h_args: list[tuple[int, int] | tuple[int] | tuple[()]] = []
+        focus_position = self.focus_position
+
+        for i, (w, (f, height)) in enumerate(self.contents):
+            if isinstance(w, Widget):
+                w_sizing = w.sizing()
+            else:
+                warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3)
+                w_sizing = frozenset((Sizing.FLOW, Sizing.BOX))
+
+            focused = focus and i == focus_position
+
+            if f == WHSettings.GIVEN:
+                heights.append(height)
+                w_h_args.append((maxcol, height))
+            elif Sizing.FLOW in w_sizing:
+                heights.append(w.rows((maxcol,), focus=focused))
+                w_h_args.append((maxcol,))
+            elif Sizing.FIXED in w_sizing and f == WHSettings.PACK:
+                heights.append(w.pack((), focused)[1])
+                w_h_args.append(())
+            else:
+                warnings.warn(
+                    f"Unusual widget {i} sizing {w_sizing} for {f.upper()}). "
+                    f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for height calculation",
+                    PileWarning,
+                    stacklevel=3,
+                )
+                heights.append(w.rows((maxcol,), focus=focused))
+                w_h_args.append((maxcol,))
+
+        return (widths, tuple(heights), tuple(w_h_args))
+
+    def get_rows_sizes(
+        self,
+        size: tuple[int, int] | tuple[int] | tuple[()],
+        focus: bool = False,
+    ) -> tuple[Sequence[int], Sequence[int], Sequence[tuple[int, int] | tuple[int] | tuple[()]]]:
+        """Get rows widths, heights and render size parameters"""
+        if not size:
+            return self._get_fixed_rows_sizes(focus=focus)
+        if len(size) == 1:
+            return self._get_flow_rows_sizes(size, focus=focus)
+
+        maxcol, maxrow = size
+        if not self.contents:
+            return (maxcol,), (maxrow,), ()
+
+        remaining: int = maxrow
+
+        widths: Sequence[int] = (maxcol,) * len(self.contents)
+        heights: dict[int, int] = {}
+        weighted: dict[int, int] = {}
+        w_h_args: dict[int, tuple[int, int] | tuple[int] | tuple[()]] = {}
+        focus_position = self.focus_position
+
+        for i, (w, (f, height)) in enumerate(self.contents):
+            if isinstance(w, Widget):
+                w_sizing = w.sizing()
+            else:
+                warnings.warn(f"{w!r} is not a Widget", PileWarning, stacklevel=3)
+                w_sizing = frozenset((Sizing.FLOW, Sizing.BOX))
+
+            focused = focus and i == focus_position
+
+            if f == WHSettings.GIVEN:
+                heights[i] = height
+                w_h_args[i] = (maxcol, height)
+                remaining -= height
+            elif f == WHSettings.PACK or len(size) == 1:
+                if Sizing.FLOW in w_sizing:
+                    w_h_arg: tuple[int] | tuple[()] = (maxcol,)
+                elif Sizing.FIXED in w_sizing and f == WHSettings.PACK:
+                    w_h_arg = ()
+                else:
+                    warnings.warn(
+                        f"Unusual widget {i} sizing {w_sizing} for {f.upper()}). "
+                        f"Assuming wrong sizing and using {Sizing.FLOW.upper()} for height calculation",
+                        PileWarning,
+                        stacklevel=3,
+                    )
+                    w_h_arg = (maxcol,)
+
+                item_height = w.pack(w_h_arg, focused)[1]
+                heights[i] = item_height
+                w_h_args[i] = w_h_arg
+                remaining -= item_height
+            elif height:
+                weighted[i] = height
+            else:
+                heights[i] = 0
+                w_h_args[i] = (maxcol, 0)  # zero-weighted items treated as ('given', 0)
+
+        sum_weight = sum(weighted.values())
+        if remaining <= 0 and focus_position in weighted:
+            # We need to hide some widgets: focused part will be not displayed by default
+            # At this place we have to operate also negative "remaining" to be sure that widget really fit
+            before = []
+            after = []
+            for idx, height in heights.items():
+                if height:
+                    if idx < focus_position:
+                        before.append(idx)
+                    else:
+                        after.append(idx)
+
+            # Try to move to the center
+            offset = len(before) - len(after)
+            if not offset:
+                indexes = (element for pair in zip(after[::-1], before) for element in pair)
+            elif offset > 0:
+                indexes = (
+                    *before[:offset],
+                    *(element for pair in zip(after[::-1], before[offset:]) for element in pair),
+                )
+            else:
+                indexes = (
+                    *after[-1 : offset - 1 : -1],
+                    *(element for pair in zip(after[offset - 1 :: -1], before) for element in pair),
+                )
+
+            for idx in indexes:
+                height, heights[idx] = heights[idx], 0
+                remaining += height
+                if remaining > 0:
+                    break
+
+        remaining = max(remaining, 0)
+
+        for idx in sorted(weighted, key=lambda idx: (idx != focus_position, idx)):
+            # We have to sort weighted items way that focused widget will gain render priority
+            if remaining == 0:
+                rows = 0
+            else:
+                rows = int(float(remaining) * weighted[idx] / sum_weight + 0.5)
+                if not rows and idx == focus_position:
+                    # Special case: we have to force as minimum 1 row for focused widget to prevent broken behaviour
+                    rows = 1
+                remaining -= rows
+                sum_weight -= weighted[idx]
+
+            heights[idx] = rows
+            w_h_args[idx] = (maxcol, rows)
+
+        return (
+            widths,
+            tuple(heights[idx] for idx in range(len(heights))),
+            tuple(w_h_args[idx] for idx in range(len(w_h_args))),
+        )
+
+    def pack(self, size: tuple[()] | tuple[int] | tuple[int, int] = (), focus: bool = False) -> tuple[int, int]:
+        """Get packed sized for widget."""
+        if size:
+            return super().pack(size, focus)
+        widths, heights, _ = self.get_rows_sizes(size, focus)
+        return (max(widths), sum(heights))
+
+    def get_item_rows(self, size: tuple[int] | tuple[int, int], focus: bool) -> list[int]:
+        """A list of the number of rows used by each widget in self.contents.
+
+        This method is a normally used only by `get_item_size` for the BOX case..
+        """
+        return list(self.get_rows_sizes(size, focus)[1])
+
+    def render(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        focus: bool = False,
+    ) -> SolidCanvas | CompositeCanvas:
+        _widths, heights, size_args = self.get_rows_sizes(size, focus)
+
+        combinelist = []
+        for i, (height, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)):
+            item_focus = self.focus == w
+            canv = None
+            if height > 0:
+                canv = w.render(w_size, focus=focus and item_focus)
+
+            if canv:
+                combinelist.append((canv, i, item_focus))
+
+        if not combinelist:
+            return SolidCanvas(" ", size[0], (*size[1:], 0)[0])
+
+        out = CanvasCombine(combinelist)
+        if len(size) == 2 and size[1] != out.rows():
+            # flow/fixed widgets rendered too large/small
+            out = CompositeCanvas(out)
+            out.pad_trim_top_bottom(0, size[1] - out.rows())
+        return out
+
+    def get_cursor_coords(self, size: tuple[()] | tuple[int] | tuple[int, int]) -> tuple[int, int] | None:
+        """Return the cursor coordinates of the focus widget."""
+        if not self.selectable():
+            return None
+        if not hasattr(self.focus, "get_cursor_coords"):
+            return None
+
+        i = self.focus_position
+        _widths, heights, size_args = self.get_rows_sizes(size, focus=True)
+        if (coords := self.focus.get_cursor_coords(size_args[i])) is not None:
+            x, y = coords
+            if i > 0:
+                y += sum(heights[:i])
+
+            return x, y
+
+        return None
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        return sum(self.get_rows_sizes(size, focus)[1])
+
+    def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None:
+        """Pass the keypress to the widget in focus.
+
+        Unhandled 'up' and 'down' keys may cause a focus change.
+        """
+        if not self.contents:
+            return key
+
+        i = self.focus_position
+        _widths, heights, size_args = self.get_rows_sizes(size, focus=self.selectable())
+        if self.selectable():
+            key = self.focus.keypress(size_args[i], key)
+            if self._command_map[key] not in {Command.UP, Command.DOWN}:
+                return key
+
+        if self._command_map[key] == Command.UP:
+            candidates = tuple(range(i - 1, -1, -1))  # count backwards to 0
+        else:  # self._command_map[key] == 'cursor down'
+            candidates = tuple(range(i + 1, len(self.contents)))
+
+        for j in candidates:
+            if not self.contents[j][0].selectable():
+                continue
+
+            self._update_pref_col_from_focus(size_args[self.focus_position])
+            self.focus_position = j
+            if not hasattr(self.focus, "move_cursor_to_coords"):
+                return None
+
+            rows = heights[j]
+            if self._command_map[key] == Command.UP:
+                rowlist = tuple(range(rows - 1, -1, -1))
+            else:  # self._command_map[key] == 'cursor down'
+                rowlist = tuple(range(rows))
+            for row in rowlist:
+                if self.focus.move_cursor_to_coords(size_args[self.focus_position], self.pref_col, row):
+                    break
+            return None
+
+        # nothing to select
+        return key
+
+    def _update_pref_col_from_focus(self, w_size: tuple[()] | tuple[int] | tuple[int, int]) -> None:
+        """Update self.pref_col from the focus widget."""
+
+        if not hasattr(self.focus, "get_pref_col"):
+            return
+
+        if (pref_col := self.focus.get_pref_col(w_size)) is not None:
+            self.pref_col = pref_col
+
+    def move_cursor_to_coords(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        col: int,
+        row: int,
+    ) -> bool:
+        """Capture pref col and set new focus."""
+        self.pref_col = col
+
+        # FIXME guessing focus==True
+        focus = True
+        wrow = 0
+        _widths, heights, size_args = self.get_rows_sizes(size, focus=focus)
+        for i, (r, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)):  # noqa: B007
+            if wrow + r > row:
+                break
+            wrow += r
+        else:
+            return False
+
+        if not w.selectable():
+            return False
+
+        if hasattr(w, "move_cursor_to_coords") and w.move_cursor_to_coords(w_size, col, row - wrow) is False:
+            return False
+
+        self.focus_position = i
+        return True
+
+    def mouse_event(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """Pass the event to the contained widget.
+
+        May change focus on button 1 press.
+        """
+        wrow = 0
+        _widths, heights, size_args = self.get_rows_sizes(size, focus=focus)
+
+        for i, (height, w_size, (w, _)) in enumerate(zip(heights, size_args, self.contents)):  # noqa: B007
+            if wrow + height > row:
+                target_row = row - wrow
+                break
+            wrow += height
+        else:
+            return False
+
+        if is_mouse_press(event) and button == 1 and w.selectable():
+            self.focus_position = i
+
+        if not hasattr(w, "mouse_event"):
+            warnings.warn(
+                f"{w.__class__.__module__}.{w.__class__.__name__} is not subclass of Widget",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            return False
+
+        return w.mouse_event(w_size, event, button, col, target_row, focus and self.focus == w)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/popup.py b/python/user_packages/Python313/site-packages/urwid/widget/popup.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e1a3aeea8791497b3f1a4481bacc3e917343ed5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/popup.py
@@ -0,0 +1,173 @@
+# Urwid Window-Icon-Menu-Pointer-style widget classes
+#    Copyright (C) 2004-2011  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+from __future__ import annotations
+
+import typing
+
+from urwid.canvas import CompositeCanvas
+
+from .constants import Align, Sizing, VAlign
+from .overlay import Overlay
+from .widget import delegate_to_widget_mixin
+from .widget_decoration import WidgetDecoration
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import TypedDict
+
+    from urwid.canvas import Canvas
+
+    from .widget import Widget
+
+    class PopUpParametersModel(TypedDict):
+        left: int
+        top: int
+        overlay_width: int
+        overlay_height: int
+
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class PopUpLauncher(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]):
+    def __init__(self, original_widget: [WrappedWidget]) -> None:
+        super().__init__(original_widget)
+        self._pop_up_widget = None
+
+    def create_pop_up(self) -> Widget:
+        """
+        Subclass must override this method and return a widget
+        to be used for the pop-up.  This method is called once each time
+        the pop-up is opened.
+        """
+        raise NotImplementedError("Subclass must override this method")
+
+    def get_pop_up_parameters(self) -> PopUpParametersModel:
+        """
+        Subclass must override this method and have it return a dict, eg:
+
+        {'left':0, 'top':1, 'overlay_width':30, 'overlay_height':4}
+
+        This method is called each time this widget is rendered.
+        """
+        raise NotImplementedError("Subclass must override this method")
+
+    def open_pop_up(self) -> None:
+        self._pop_up_widget = self.create_pop_up()
+        self._invalidate()
+
+    def close_pop_up(self) -> None:
+        self._pop_up_widget = None
+        self._invalidate()
+
+    def render(self, size, focus: bool = False) -> CompositeCanvas | Canvas:
+        canv = super().render(size, focus)
+        if self._pop_up_widget:
+            canv = CompositeCanvas(canv)
+            canv.set_pop_up(self._pop_up_widget, **self.get_pop_up_parameters())
+        return canv
+
+
+class PopUpTarget(WidgetDecoration[WrappedWidget]):
+    # FIXME: this whole class is a terrible hack and must be fixed when layout and rendering are separated
+    _sizing = frozenset((Sizing.BOX,))
+    _selectable = True
+
+    def __init__(self, original_widget: WrappedWidget) -> None:
+        super().__init__(original_widget)
+        self._pop_up = None
+        self._current_widget = self._original_widget
+
+    def _update_overlay(self, size: tuple[int, int], focus: bool) -> None:
+        canv = self._original_widget.render(size, focus=focus)
+        self._cache_original_canvas = canv  # imperfect performance hack
+
+        if pop_up := canv.get_pop_up():
+            left, top, (w, overlay_width, overlay_height) = pop_up
+            if self._pop_up != w:
+                self._pop_up = w
+                self._current_widget = Overlay(
+                    top_w=w,
+                    bottom_w=self._original_widget,
+                    align=Align.LEFT,
+                    width=overlay_width,
+                    valign=VAlign.TOP,
+                    height=overlay_height,
+                    left=left,
+                    top=top,
+                )
+            else:
+                self._current_widget.set_overlay_parameters(
+                    align=Align.LEFT,
+                    width=overlay_width,
+                    valign=VAlign.TOP,
+                    height=overlay_height,
+                    left=left,
+                    top=top,
+                )
+        else:
+            self._pop_up = None
+            self._current_widget = self._original_widget
+
+    def render(self, size: tuple[int, int], focus: bool = False) -> Canvas:
+        self._update_overlay(size, focus)
+        return self._current_widget.render(size, focus=focus)
+
+    def get_cursor_coords(self, size: tuple[int, int]) -> tuple[int, int] | None:
+        self._update_overlay(size, True)
+        return self._current_widget.get_cursor_coords(size)
+
+    def get_pref_col(self, size: tuple[int, int]) -> int:
+        self._update_overlay(size, True)
+        return self._current_widget.get_pref_col(size)
+
+    def keypress(self, size: tuple[int, int], key: str) -> str | None:
+        self._update_overlay(size, True)
+        return self._current_widget.keypress(size, key)
+
+    def move_cursor_to_coords(self, size: tuple[int, int], x: int, y: int):
+        self._update_overlay(size, True)
+        return self._current_widget.move_cursor_to_coords(size, x, y)
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        self._update_overlay(size, focus)
+        return self._current_widget.mouse_event(size, event, button, col, row, focus)
+
+    def pack(self, size: tuple[int, int] | None = None, focus: bool = False) -> tuple[int, int]:
+        self._update_overlay(size, focus)
+        return self._current_widget.pack(size)
+
+
+def _test():
+    import doctest
+
+    doctest.testmod()
+
+
+if __name__ == "__main__":
+    _test()
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/progress_bar.py b/python/user_packages/Python313/site-packages/urwid/widget/progress_bar.py
new file mode 100644
index 0000000000000000000000000000000000000000..e18638cafb7a47938ca675ab8d94e9ea5ddc739d
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/progress_bar.py
@@ -0,0 +1,144 @@
+from __future__ import annotations
+
+import typing
+
+from .constants import BAR_SYMBOLS, Align, Sizing, WrapMode
+from .text import Text
+from .widget import Widget
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable
+
+    from urwid.canvas import TextCanvas
+
+
+class ProgressBar(Widget):
+    _sizing = frozenset([Sizing.FLOW])
+
+    eighths = BAR_SYMBOLS.HORISONTAL[:8]  # Full width line is made by style
+
+    text_align = Align.CENTER
+
+    def __init__(
+        self,
+        normal: Hashable | None,
+        complete: Hashable | None,
+        current: int = 0,
+        done: int = 100,
+        satt: Hashable | None = None,
+    ) -> None:
+        """
+        :param normal: display attribute for incomplete part of progress bar
+        :param complete: display attribute for complete part of progress bar
+        :param current: current progress
+        :param done: progress amount at 100%
+        :param satt: display attribute for smoothed part of bar where the
+                     foreground of satt corresponds to the normal part and the
+                     background corresponds to the complete part.
+                     If satt is ``None`` then no smoothing will be done.
+
+        >>> from urwid import LineBox
+        >>> pb = ProgressBar("a", "b")
+        >>> pb
+        
+        >>> print(pb.get_text())
+        0 %
+        >>> pb.set_completion(34.42)
+        >>> print(pb.get_text())
+        34 %
+        >>> class CustomProgressBar(ProgressBar):
+        ...     def get_text(self):
+        ...         return "Foobar"
+        >>> cpb = CustomProgressBar("a", "b")
+        >>> print(cpb.get_text())
+        Foobar
+        >>> for x in range(101):
+        ...     cpb.set_completion(x)
+        ...     s = cpb.render((10,))
+        >>> cpb2 = CustomProgressBar("a", "b", satt="c")
+        >>> for x in range(101):
+        ...     cpb2.set_completion(x)
+        ...     s = cpb2.render((10,))
+        >>> pb = ProgressBar("a", "b", satt="c")
+        >>> pb.set_completion(34.56)
+        >>> print(LineBox(pb).render((20,)))
+        ┌──────────────────┐
+        │      ▏34 %       │
+        └──────────────────┘
+        """
+        super().__init__()
+        self.normal = normal
+        self.complete = complete
+        self._current = current
+        self._done = done
+        self.satt = satt
+
+    def set_completion(self, current: int) -> None:
+        """
+        current -- current progress
+        """
+        self._current = current
+        self._invalidate()
+
+    current = property(lambda self: self._current, set_completion)
+
+    @property
+    def done(self):
+        return self._done
+
+    @done.setter
+    def done(self, done):
+        """
+        done -- progress amount at 100%
+        """
+        self._done = done
+        self._invalidate()
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        return 1
+
+    def get_text(self) -> str:
+        """
+        Return the progress bar percentage text.
+        You can override this method to display custom text.
+        """
+        percent = min(100, max(0, int(self.current * 100 / self.done)))
+        return f"{percent!s} %"
+
+    def render(
+        self,
+        size: tuple[int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> TextCanvas:
+        """
+        Render the progress bar.
+        """
+        # pylint: disable=protected-access
+        (maxcol,) = size
+        c = Text(self.get_text(), self.text_align, WrapMode.CLIP).render((maxcol,))
+
+        cf = float(self.current) * maxcol / self.done
+        ccol_dirty = int(cf)
+        ccol = len(c._text[0][:ccol_dirty].decode("utf-8", "ignore").encode("utf-8"))
+        cs = 0
+        if self.satt is not None:
+            cs = int((cf - ccol) * 8)
+        if ccol < 0 or (ccol == cs == 0):
+            c._attr = [[(self.normal, maxcol)]]
+        elif ccol >= maxcol:
+            c._attr = [[(self.complete, maxcol)]]
+        elif cs and c._text[0][ccol] == 32:
+            t = c._text[0]
+            cenc = self.eighths[cs].encode("utf-8")
+            c._text[0] = t[:ccol] + cenc + t[ccol + 1 :]
+            a = []
+            if ccol > 0:
+                a.append((self.complete, ccol))
+            a.append((self.satt, len(cenc)))
+            if maxcol - ccol - 1 > 0:
+                a.append((self.normal, maxcol - ccol - 1))
+            c._attr = [a]
+            c._cs = [[(None, len(c._text[0]))]]
+        else:
+            c._attr = [[(self.complete, ccol), (self.normal, maxcol - ccol)]]
+        return c
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/scrollable.py b/python/user_packages/Python313/site-packages/urwid/widget/scrollable.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e14c5db324987ba7d4822b5f16d7c73694bfabb
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/scrollable.py
@@ -0,0 +1,663 @@
+# Copyright (C) 2024 Urwid developers
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+#
+# Copyright (C) 2017-2024 rndusr (https://github.com/rndusr)
+# Re-licensed from gpl-3.0 with author permission.
+# Permission comment link: https://github.com/markqvist/NomadNet/pull/46#issuecomment-1892712616
+
+from __future__ import annotations
+
+import contextlib
+import enum
+import typing
+
+from .constants import BOX_SYMBOLS, SHADE_SYMBOLS, Sizing
+from .widget_decoration import WidgetDecoration, WidgetError
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Iterator
+
+    from typing_extensions import Literal
+
+    from urwid import Canvas, CompositeCanvas
+
+    from .widget import Widget
+
+
+__all__ = ("ScrollBar", "Scrollable", "ScrollableError", "ScrollbarSymbols")
+
+
+WrappedWidget = typing.TypeVar("WrappedWidget", bound="SupportsScroll")
+
+
+class ScrollableError(WidgetError):
+    """Scrollable specific widget errors."""
+
+
+# Scroll actions
+SCROLL_LINE_UP = "line up"
+SCROLL_LINE_DOWN = "line down"
+SCROLL_PAGE_UP = "page up"
+SCROLL_PAGE_DOWN = "page down"
+SCROLL_TO_TOP = "to top"
+SCROLL_TO_END = "to end"
+
+# Scrollbar positions
+SCROLLBAR_LEFT = "left"
+SCROLLBAR_RIGHT = "right"
+
+
+class ScrollbarSymbols(str, enum.Enum):
+    """Common symbols suitable for scrollbar."""
+
+    FULL_BLOCK = SHADE_SYMBOLS.FULL_BLOCK
+    DARK_SHADE = SHADE_SYMBOLS.DARK_SHADE
+    MEDIUM_SHADE = SHADE_SYMBOLS.MEDIUM_SHADE
+    LITE_SHADE = SHADE_SYMBOLS.LITE_SHADE
+
+    DRAWING_LIGHT = BOX_SYMBOLS.LIGHT.VERTICAL
+    DRAWING_LIGHT_2_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_2_DASH
+    DRAWING_LIGHT_3_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_3_DASH
+    DRAWING_LIGHT_4_DASH = BOX_SYMBOLS.LIGHT.VERTICAL_4_DASH
+
+    DRAWING_HEAVY = BOX_SYMBOLS.HEAVY.VERTICAL
+    DRAWING_HEAVY_2_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_2_DASH
+    DRAWING_HEAVY_3_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_3_DASH
+    DRAWING_HEAVY_4_DASH = BOX_SYMBOLS.HEAVY.VERTICAL_4_DASH
+
+    DRAWING_DOUBLE = BOX_SYMBOLS.DOUBLE.VERTICAL
+
+
+@typing.runtime_checkable
+class WidgetProto(typing.Protocol):
+    """Protocol for widget.
+
+    Due to protocol cannot inherit non-protocol bases, define several obligatory Widget methods.
+    """
+
+    # Base widget methods (from Widget)
+    def sizing(self) -> frozenset[Sizing]: ...
+
+    def selectable(self) -> bool: ...
+
+    def pack(self, size: tuple[int, int], focus: bool = False) -> tuple[int, int]: ...
+
+    @property
+    def base_widget(self) -> Widget:
+        raise NotImplementedError
+
+    def keypress(self, size: tuple[int, int], key: str) -> str | None: ...
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None: ...
+
+    def render(self, size: tuple[int, int], focus: bool = False) -> Canvas: ...
+
+
+@typing.runtime_checkable
+class SupportsScroll(WidgetProto, typing.Protocol):
+    """Scroll specific methods."""
+
+    def get_scrollpos(self, size: tuple[int, int], focus: bool = False) -> int: ...
+
+    def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int: ...
+
+
+@typing.runtime_checkable
+class SupportsRelativeScroll(WidgetProto, typing.Protocol):
+    """Relative scroll-specific methods."""
+
+    def require_relative_scroll(self, size: tuple[int, int], focus: bool = False) -> bool: ...
+
+    def get_first_visible_pos(self, size: tuple[int, int], focus: bool = False) -> int: ...
+
+    def get_visible_amount(self, size: tuple[int, int], focus: bool = False) -> int: ...
+
+
+def orig_iter(w: Widget) -> Iterator[Widget]:
+    visited = {w}
+    yield w
+    while (w := getattr(w, "original_widget", w)) not in visited:
+        visited.add(w)
+        yield w
+
+
+class Scrollable(WidgetDecoration[WrappedWidget]):
+    def sizing(self) -> frozenset[Sizing]:
+        return frozenset((Sizing.BOX,))
+
+    def selectable(self) -> bool:
+        return True
+
+    def __init__(self, widget: WrappedWidget, force_forward_keypress: bool = False) -> None:
+        """Box widget that makes a fixed or flow widget vertically scrollable
+
+        .. note::
+            Focusable widgets are handled, including switching focus, but possibly not intuitively,
+            depending on the arrangement of widgets.
+
+            When switching focus to a widget that is ouside of the visible part of the original widget,
+            the canvas scrolls up/down to the focused widget.
+
+            It would be better to scroll until the next focusable widget is in sight first.
+            But for that to work we must somehow obtain a list of focusable rows in the original canvas.
+        """
+        if not widget.sizing() & frozenset((Sizing.FIXED, Sizing.FLOW)):
+            raise ValueError(f"Not a fixed or flow widget: {widget!r}")
+
+        self._trim_top = 0
+        self._scroll_action = None
+        self._forward_keypress = None
+        self._old_cursor_coords = None
+        self._rows_max_cached = 0
+        self.force_forward_keypress = force_forward_keypress
+        super().__init__(widget)
+
+    def render(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> CompositeCanvas:
+        from urwid import canvas
+
+        maxcol, maxrow = size
+
+        def automove_cursor() -> None:
+            ch = 0
+            last_hidden = False
+            first_visible = False
+            for pwi, (w, _o) in enumerate(ow.contents):
+                wcanv = w.render((maxcol,))
+
+                if wh := wcanv.rows():
+                    ch += wh
+
+                if not last_hidden and ch >= self._trim_top:
+                    last_hidden = True
+
+                elif last_hidden:
+                    if not first_visible:
+                        first_visible = True
+
+                    if not w.selectable():
+                        continue
+
+                    ow.focus_item = pwi
+
+                    st = None
+                    nf = ow.get_focus()
+                    if hasattr(nf, "key_timeout"):
+                        st = nf
+                    elif hasattr(nf, "original_widget"):
+                        no = nf.original_widget
+                        if hasattr(no, "original_widget"):
+                            st = no.original_widget
+                        elif hasattr(no, "key_timeout"):
+                            st = no
+
+                    if st and hasattr(st, "key_timeout") and callable(getattr(st, "keypress", None)):
+                        st.keypress(None, None)
+
+                    break
+
+        # Render complete original widget
+        ow = self._original_widget
+        ow_size = self._get_original_widget_size(size)
+        canv_full = ow.render(ow_size, focus)
+
+        # Make full canvas editable
+        canv = canvas.CompositeCanvas(canv_full)
+        canv_cols, canv_rows = canv.cols(), canv.rows()
+
+        if canv_cols <= maxcol and (pad_width := maxcol - canv_cols) > 0:
+            # Canvas is narrower than available horizontal space
+            canv.pad_trim_left_right(0, pad_width)
+
+        if canv_rows <= maxrow and (fill_height := maxrow - canv_rows) > 0:
+            # Canvas is lower than available vertical space
+            canv.pad_trim_top_bottom(0, fill_height)
+
+        if canv_cols <= maxcol and canv_rows <= maxrow:
+            # Canvas is small enough to fit without trimming
+            return canv
+
+        self._adjust_trim_top(canv, size)
+
+        # Trim canvas if necessary
+        trim_top = self._trim_top
+        trim_end = canv_rows - maxrow - trim_top
+        trim_right = canv_cols - maxcol
+        if trim_top > 0:
+            canv.trim(trim_top)
+        if trim_end > 0:
+            canv.trim_end(trim_end)
+        if trim_right > 0:
+            canv.pad_trim_left_right(0, -trim_right)
+
+        # Disable cursor display if cursor is outside of visible canvas parts
+        if canv.cursor is not None:
+            # Pylint check acts here a bit weird.
+            _curscol, cursrow = canv.cursor  # pylint: disable=unpacking-non-sequence,useless-suppression
+            if cursrow >= maxrow or cursrow < 0:
+                canv.cursor = None
+
+        # Figure out whether we should forward keypresses to original widget
+        if canv.cursor is not None:
+            # Trimmed canvas contains the cursor, e.g. in an Edit widget
+            self._forward_keypress = True
+        elif canv_full.cursor is not None:
+            # Full canvas contains the cursor, but scrolled out of view
+            self._forward_keypress = False
+
+            # Reset cursor position on page/up down scrolling
+            if getattr(ow, "automove_cursor_on_scroll", False):
+                with contextlib.suppress(Exception):
+                    automove_cursor()
+
+        else:
+            # Original widget does not have a cursor, but may be selectable
+
+            # FIXME: Using ow.selectable() is bad because the original
+            # widget may be selectable because it's a container widget with
+            # a key-grabbing widget that is scrolled out of view.
+            # ow.selectable() returns True anyway because it doesn't know
+            # how we trimmed our canvas.
+            #
+            # To fix this, we need to resolve ow.focus and somehow
+            # ask canv whether it contains bits of the focused widget.  I
+            # can't see a way to do that.
+            self._forward_keypress = ow.selectable()
+
+        return canv
+
+    def keypress(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        from urwid.command_map import Command
+
+        # Maybe offer key to original widget
+        if self._forward_keypress or self.force_forward_keypress:
+            ow = self._original_widget
+            ow_size = self._get_original_widget_size(size)
+
+            # Remember the previous cursor position if possible
+            if hasattr(ow, "get_cursor_coords"):
+                self._old_cursor_coords = ow.get_cursor_coords(ow_size)
+
+            key = ow.keypress(ow_size, key)
+            if key is None:
+                return None
+
+        # Handle up/down, page up/down, etc.
+        command_map = self._command_map
+        if command_map[key] == Command.UP:
+            self._scroll_action = SCROLL_LINE_UP
+        elif command_map[key] == Command.DOWN:
+            self._scroll_action = SCROLL_LINE_DOWN
+
+        elif command_map[key] == Command.PAGE_UP:
+            self._scroll_action = SCROLL_PAGE_UP
+        elif command_map[key] == Command.PAGE_DOWN:
+            self._scroll_action = SCROLL_PAGE_DOWN
+
+        elif command_map[key] == Command.MAX_LEFT:  # 'home'
+            self._scroll_action = SCROLL_TO_TOP
+        elif command_map[key] == Command.MAX_RIGHT:  # 'end'
+            self._scroll_action = SCROLL_TO_END
+
+        else:
+            return key
+
+        self._invalidate()
+        return None
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        ow = self._original_widget
+        if hasattr(ow, "mouse_event"):
+            ow_size = self._get_original_widget_size(size)
+            row += self._trim_top
+            return ow.mouse_event(ow_size, event, button, col, row, focus)
+
+        return False
+
+    def _adjust_trim_top(self, canv: Canvas, size: tuple[int, int]) -> None:
+        """Adjust self._trim_top according to self._scroll_action"""
+        action = self._scroll_action
+        self._scroll_action = None
+
+        _maxcol, maxrow = size
+        trim_top = self._trim_top
+        canv_rows = canv.rows()
+
+        if trim_top < 0:
+            # Negative trim_top values use bottom of canvas as reference
+            trim_top = canv_rows - maxrow + trim_top + 1
+
+        if canv_rows <= maxrow:
+            self._trim_top = 0  # Reset scroll position
+            return
+
+        def ensure_bounds(new_trim_top: int) -> int:
+            return max(0, min(canv_rows - maxrow, new_trim_top))
+
+        if action == SCROLL_LINE_UP:
+            self._trim_top = ensure_bounds(trim_top - 1)
+        elif action == SCROLL_LINE_DOWN:
+            self._trim_top = ensure_bounds(trim_top + 1)
+
+        elif action == SCROLL_PAGE_UP:
+            self._trim_top = ensure_bounds(trim_top - maxrow + 1)
+        elif action == SCROLL_PAGE_DOWN:
+            self._trim_top = ensure_bounds(trim_top + maxrow - 1)
+
+        elif action == SCROLL_TO_TOP:
+            self._trim_top = 0
+        elif action == SCROLL_TO_END:
+            self._trim_top = canv_rows - maxrow
+
+        else:
+            self._trim_top = ensure_bounds(trim_top)
+
+        # If the cursor was moved by the most recent keypress, adjust trim_top
+        # so that the new cursor position is within the displayed canvas part.
+        # But don't do this if the cursor is at the top/bottom edge so we can still scroll out
+        if self._old_cursor_coords is not None and self._old_cursor_coords != canv.cursor and canv.cursor is not None:
+            self._old_cursor_coords = None
+            _curscol, cursrow = canv.cursor
+            if cursrow < self._trim_top:
+                self._trim_top = cursrow
+            elif cursrow >= self._trim_top + maxrow:
+                self._trim_top = max(0, cursrow - maxrow + 1)
+
+    def _get_original_widget_size(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+    ) -> tuple[int] | tuple[()]:
+        ow = self._original_widget
+        sizing = ow.sizing()
+        if Sizing.FLOW in sizing:
+            return (size[0],)
+        if Sizing.FIXED in sizing:
+            return ()
+        raise ScrollableError(f"{ow!r} sizing is not supported")
+
+    def get_scrollpos(self, size: tuple[int, int] | None = None, focus: bool = False) -> int:
+        """Current scrolling position.
+
+        Lower limit is 0, upper limit is the maximum number of rows with the given maxcol minus maxrow.
+
+        ..note::
+            The returned value may be too low or too high if the position has
+            changed but the widget wasn't rendered yet.
+        """
+        return self._trim_top
+
+    def set_scrollpos(self, position: typing.SupportsInt) -> None:
+        """Set scrolling position
+
+        If `position` is positive it is interpreted as lines from the top.
+        If `position` is negative it is interpreted as lines from the bottom.
+
+        Values that are too high or too low values are automatically adjusted during rendering.
+        """
+        self._trim_top = int(position)
+        self._invalidate()
+
+    def rows_max(self, size: tuple[int, int] | None = None, focus: bool = False) -> int:
+        """Return the number of rows for `size`
+
+        If `size` is not given, the currently rendered number of rows is returned.
+        """
+        if size is not None:
+            ow = self._original_widget
+            ow_size = self._get_original_widget_size(size)
+            sizing = ow.sizing()
+            if Sizing.FIXED in sizing:
+                self._rows_max_cached = ow.pack(ow_size, focus)[1]
+            elif Sizing.FLOW in sizing:
+                self._rows_max_cached = ow.rows(ow_size, focus)
+            else:
+                raise ScrollableError(f"Not a flow/box widget: {self._original_widget!r}")
+        return self._rows_max_cached
+
+
+class ScrollBar(WidgetDecoration[WrappedWidget]):
+    Symbols = ScrollbarSymbols
+
+    def sizing(self) -> frozenset[Sizing]:
+        return frozenset((Sizing.BOX,))
+
+    def selectable(self) -> bool:
+        return True
+
+    def __init__(
+        self,
+        widget: WrappedWidget,
+        thumb_char: str = ScrollbarSymbols.FULL_BLOCK,
+        trough_char: str = " ",
+        side: Literal["left", "right"] = SCROLLBAR_RIGHT,
+        width: int = 1,
+    ) -> None:
+        """Box widget that adds a scrollbar to `widget`
+
+        `widget` must be a box widget with the following methods:
+          - `get_scrollpos` takes the arguments `size` and `focus` and returns the index of the first visible row.
+          - `set_scrollpos` (optional; needed for mouse click support) takes the index of the first visible row.
+          - `rows_max` takes `size` and `focus` and returns the total number of rows `widget` can render.
+
+        `thumb_char` is the character used for the scrollbar handle.
+        `trough_char` is used for the space above and below the handle.
+        `side` must be 'left' or 'right'.
+        `width` specifies the number of columns the scrollbar uses.
+        """
+        if Sizing.BOX not in widget.sizing():
+            raise ValueError(f"Not a box widget: {widget!r}")
+
+        if not any(isinstance(w, SupportsScroll) for w in orig_iter(widget)):
+            raise TypeError(f"Not a scrollable widget: {widget!r}")
+
+        super().__init__(widget)
+        self._thumb_char = thumb_char
+        self._trough_char = trough_char
+        self.scrollbar_side = side
+        self.scrollbar_width = max(1, width)
+        self._original_widget_size = (0, 0)
+
+    def render(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> Canvas:
+        from urwid import canvas
+
+        def render_no_scrollbar() -> Canvas:
+            self._original_widget_size = size
+            return ow.render(size, focus)
+
+        def render_for_scrollbar() -> Canvas:
+            self._original_widget_size = ow_size
+            return ow.render(ow_size, focus)
+
+        maxcol, maxrow = size
+
+        ow_size = (max(0, maxcol - self._scrollbar_width), maxrow)
+        sb_width = maxcol - ow_size[0]
+
+        ow = self._original_widget
+        ow_base = self.scrolling_base_widget
+
+        # Use hasattr instead of protocol: hasattr will return False in case of getattr raise AttributeError
+        # Use __length_hint__ first since it's less resource intensive
+        use_relative = (
+            isinstance(ow_base, SupportsRelativeScroll)
+            and any(hasattr(ow_base, attrib) for attrib in ("__length_hint__", "__len__"))
+            and ow_base.require_relative_scroll(size, focus)
+        )
+
+        if use_relative:
+            # `operator.length_hint` is Protocol (Spec) over class based and can end false-negative on the instance
+            # use length_hint-like approach with safe `AttributeError` handling
+            ow_len = getattr(ow_base, "__len__", getattr(ow_base, "__length_hint__", int))()
+            ow_canv = render_for_scrollbar()
+            visible_amount = ow_base.get_visible_amount(ow_size, focus)
+            pos = ow_base.get_first_visible_pos(ow_size, focus)
+
+            # in the case of estimated length, it can be smaller than real widget length
+            ow_len = max(ow_len, visible_amount, pos)
+            posmax = ow_len - visible_amount
+            thumb_weight = min(1.0, visible_amount / max(1, ow_len))
+
+            if ow_len == visible_amount:
+                # Corner case: formally all contents indexes should be visible, but this does not mean all rows
+                use_relative = False
+
+        if not use_relative:
+            if ow_base.rows_max(size, focus) > maxrow:
+                ow_canv = render_for_scrollbar()
+                # re-calculate using wrapped size
+                ow_rows_max = ow_base.rows_max(ow_size, focus)
+                pos = ow_base.get_scrollpos(ow_size, focus)
+                posmax = ow_rows_max - maxrow
+                thumb_weight = min(1.0, maxrow / max(1, ow_rows_max))
+
+            else:
+                # Canvas fits without scrolling - no scrollbar needed
+                return render_no_scrollbar()
+
+        # Thumb shrinks/grows according to the ratio of  / 
+        thumb_height = max(1, round(thumb_weight * maxrow))  # pylint: disable=possibly-used-before-assignment
+
+        # Thumb may only touch top/bottom if the first/last row is visible
+        top_weight = float(pos) / max(1, posmax)  # pylint: disable=possibly-used-before-assignment
+        top_height = int((maxrow - thumb_height) * top_weight)
+        if top_height == 0 and top_weight > 0:
+            top_height = min(1, maxrow - thumb_height)
+
+        # Bottom part is remaining space
+        bottom_height = maxrow - thumb_height - top_height
+
+        # Create scrollbar canvas
+        # Creating SolidCanvases of correct height may result in
+        # "cviews do not fill gaps in shard_tail!" or "cviews overflow gaps in shard_tail!" exceptions.
+        # Stacking the same SolidCanvas is a workaround.
+        # https://github.com/urwid/urwid/issues/226#issuecomment-437176837
+        top = canvas.SolidCanvas(self._trough_char, sb_width, 1)
+        thumb = canvas.SolidCanvas(self._thumb_char, sb_width, 1)
+        bottom = canvas.SolidCanvas(self._trough_char, sb_width, 1)
+        sb_canv = canvas.CanvasCombine(
+            (
+                *((top, None, False) for _ in range(top_height)),
+                *((thumb, None, False) for _ in range(thumb_height)),
+                *((bottom, None, False) for _ in range(bottom_height)),
+            ),
+        )
+
+        combinelist = [
+            (ow_canv, None, True, ow_size[0]),  # pylint: disable=possibly-used-before-assignment
+            (sb_canv, None, False, sb_width),
+        ]
+
+        if self._scrollbar_side != SCROLLBAR_LEFT:
+            return canvas.CanvasJoin(combinelist)
+
+        return canvas.CanvasJoin(reversed(combinelist))
+
+    @property
+    def scrollbar_width(self) -> int:
+        """Columns the scrollbar uses"""
+        return max(1, self._scrollbar_width)
+
+    @scrollbar_width.setter
+    def scrollbar_width(self, width: typing.SupportsInt) -> None:
+        self._scrollbar_width = max(1, int(width))
+        self._invalidate()
+
+    @property
+    def scrollbar_side(self) -> Literal["left", "right"]:
+        """Where to display the scrollbar; must be 'left' or 'right'"""
+        return self._scrollbar_side
+
+    @scrollbar_side.setter
+    def scrollbar_side(self, side: Literal["left", "right"]) -> None:
+        if side not in {SCROLLBAR_LEFT, SCROLLBAR_RIGHT}:
+            raise ValueError(f'scrollbar_side must be "left" or "right", not {side!r}')
+        self._scrollbar_side = side
+        self._invalidate()
+
+    @property
+    def scrolling_base_widget(self) -> SupportsScroll | SupportsRelativeScroll:
+        """Nearest `original_widget` that is compatible with the scrolling API"""
+
+        w = self
+
+        for w in orig_iter(self):
+            if isinstance(w, SupportsScroll):
+                return w
+
+        raise ScrollableError(f"Not compatible to be wrapped by ScrollBar: {w!r}")
+
+    def keypress(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        return self._original_widget.keypress(self._original_widget_size, key)
+
+    def mouse_event(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        ow = self._original_widget
+        ow_size = self._original_widget_size
+        handled: bool | None = False
+        if hasattr(ow, "mouse_event"):
+            handled = ow.mouse_event(ow_size, event, button, col, row, focus)
+
+        if not handled and hasattr(ow, "set_scrollpos"):
+            if button == 4:  # scroll wheel up
+                pos = ow.get_scrollpos(ow_size)
+                newpos = max(pos - 1, 0)
+                ow.set_scrollpos(newpos)
+                return True
+            if button == 5:  # scroll wheel down
+                pos = ow.get_scrollpos(ow_size)
+                ow.set_scrollpos(pos + 1)
+                return True
+
+        return handled
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/solid_fill.py b/python/user_packages/Python313/site-packages/urwid/widget/solid_fill.py
new file mode 100644
index 0000000000000000000000000000000000000000..7775376296321fa04c8900a729e76f82711fe197
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/solid_fill.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from urwid.canvas import SolidCanvas
+
+from .constants import SHADE_SYMBOLS, Sizing
+from .widget import Widget
+
+
+class SolidFill(Widget):
+    """
+    A box widget that fills an area with a single character
+    """
+
+    _selectable = False
+    ignore_focus = True
+    _sizing = frozenset([Sizing.BOX])
+
+    Symbols = SHADE_SYMBOLS
+
+    def __init__(self, fill_char: str = " ") -> None:
+        """
+        :param fill_char: character to fill area with
+        :type fill_char: bytes or unicode
+
+        >>> SolidFill("8")
+        
+        """
+        super().__init__()
+        self.fill_char = fill_char
+
+    def _repr_words(self) -> list[str]:
+        return [*super()._repr_words(), repr(self.fill_char)]
+
+    def render(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        focus: bool = False,
+    ) -> SolidCanvas:
+        """
+        Render the Fill as a canvas and return it.
+
+        >>> SolidFill().render((4, 2)).text  # ... = b in Python 3
+        [...'    ', ...'    ']
+        >>> SolidFill("#").render((5, 3)).text
+        [...'#####', ...'#####', ...'#####']
+        """
+        maxcol, maxrow = size
+        return SolidCanvas(self.fill_char, maxcol, maxrow)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/text.py b/python/user_packages/Python313/site-packages/urwid/widget/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b14608f8682bc3752aca037bd47ecaf080b552
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/text.py
@@ -0,0 +1,377 @@
+from __future__ import annotations
+
+import typing
+
+from urwid import text_layout
+from urwid.canvas import apply_text_layout
+from urwid.split_repr import remove_defaults
+from urwid.str_util import calc_width
+from urwid.util import decompose_tagmarkup, get_encoding
+
+from .constants import Align, Sizing, WrapMode
+from .widget import Widget, WidgetError
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable
+
+    from typing_extensions import Literal
+
+    from urwid.canvas import TextCanvas
+
+
+class TextError(WidgetError):
+    pass
+
+
+class Text(Widget):
+    """
+    a horizontally resizeable text widget
+    """
+
+    _sizing = frozenset([Sizing.FLOW, Sizing.FIXED])
+
+    ignore_focus = True
+    _repr_content_length_max = 140
+
+    def __init__(
+        self,
+        markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        align: Literal["left", "center", "right"] | Align = Align.LEFT,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE,
+        layout: text_layout.TextLayout | None = None,
+    ) -> None:
+        """
+        :param markup: content of text widget, one of:
+
+            bytes or unicode
+              text to be displayed
+
+            (*display attribute*, *text markup*)
+              *text markup* with *display attribute* applied to all parts
+              of *text markup* with no display attribute already applied
+
+            [*text markup*, *text markup*, ... ]
+              all *text markup* in the list joined together
+
+        :type markup: :ref:`text-markup`
+        :param align: typically ``'left'``, ``'center'`` or ``'right'``
+        :type align: text alignment mode
+        :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'``
+        :type wrap: text wrapping mode
+        :param layout: defaults to a shared :class:`StandardTextLayout` instance
+        :type layout: text layout instance
+
+        >>> Text("Hello")
+        
+        >>> t = Text(("bold", "stuff"), "right", "any")
+        >>> t
+        
+        >>> print(t.text)
+        stuff
+        >>> t.attrib
+        [('bold', 5)]
+        """
+        super().__init__()
+        self._cache_maxcol: int | None = None
+        self._layout: text_layout.TextLayout = layout or text_layout.default_layout
+        self.set_text(markup)
+        self.set_layout(align, wrap, layout)
+
+    def _repr_words(self) -> list[str]:
+        """
+        Show the text in the repr in python3 format (b prefix for byte strings) and truncate if it's too long
+        """
+        first = super()._repr_words()
+        text = self.get_text()[0]
+        rest = repr(text)
+        if len(rest) > self._repr_content_length_max:
+            rest = (
+                rest[: self._repr_content_length_max * 2 // 3 - 3] + "..." + rest[-self._repr_content_length_max // 3 :]
+            )
+        return [*first, rest]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        attrs = {
+            **super()._repr_attrs(),
+            "align": self._align_mode,
+            "wrap": self._wrap_mode,
+        }
+        return remove_defaults(attrs, Text.__init__)
+
+    def _invalidate(self) -> None:
+        self._cache_maxcol = None
+        super()._invalidate()
+
+    def set_text(self, markup: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None:
+        """
+        Set content of text widget.
+
+        :param markup: see :class:`Text` for description.
+        :type markup: text markup
+
+        >>> t = Text("foo")
+        >>> print(t.text)
+        foo
+        >>> t.set_text("bar")
+        >>> print(t.text)
+        bar
+        >>> t.text = "baz"  # not supported because text stores text but set_text() takes markup
+        Traceback (most recent call last):
+        AttributeError: can't set attribute
+        """
+        self._text, self._attrib = decompose_tagmarkup(markup)
+        self._invalidate()
+
+    def get_text(self) -> tuple[str | bytes, list[tuple[Hashable, int]]]:
+        """
+        :returns: (*text*, *display attributes*)
+
+            *text*
+              complete bytes/unicode content of text widget
+
+            *display attributes*
+              run length encoded display attributes for *text*, eg.
+              ``[('attr1', 10), ('attr2', 5)]``
+
+        >>> Text("Hello").get_text()  # ... = u in Python 2
+        (...'Hello', [])
+        >>> Text(("bright", "Headline")).get_text()
+        (...'Headline', [('bright', 8)])
+        >>> Text([("a", "one"), "two", ("b", "three")]).get_text()
+        (...'onetwothree', [('a', 3), (None, 3), ('b', 5)])
+        """
+        return self._text, self._attrib
+
+    @property
+    def text(self) -> str | bytes:
+        """
+        Read-only property returning the complete bytes/unicode content
+        of this widget
+        """
+        return self.get_text()[0]
+
+    @property
+    def attrib(self) -> list[tuple[Hashable, int]]:
+        """
+        Read-only property returning the run-length encoded display
+        attributes of this widget
+        """
+        return self.get_text()[1]
+
+    def set_align_mode(self, mode: Literal["left", "center", "right"] | Align) -> None:
+        """
+        Set text alignment mode. Supported modes depend on text layout
+        object in use but defaults to a :class:`StandardTextLayout` instance
+
+        :param mode: typically ``'left'``, ``'center'`` or ``'right'``
+        :type mode: text alignment mode
+
+        >>> t = Text("word")
+        >>> t.set_align_mode("right")
+        >>> t.align
+        'right'
+        >>> t.render((10,)).text  # ... = b in Python 3
+        [...'      word']
+        >>> t.align = "center"
+        >>> t.render((10,)).text
+        [...'   word   ']
+        >>> t.align = "somewhere"
+        Traceback (most recent call last):
+        TextError: Alignment mode 'somewhere' not supported.
+        """
+        if not self.layout.supports_align_mode(mode):
+            raise TextError(f"Alignment mode {mode!r} not supported.")
+        self._align_mode = mode
+        self._invalidate()
+
+    def set_wrap_mode(self, mode: Literal["space", "any", "clip", "ellipsis"] | WrapMode) -> None:
+        """
+        Set text wrapping mode. Supported modes depend on text layout
+        object in use but defaults to a :class:`StandardTextLayout` instance
+
+        :param mode: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'``
+        :type mode: text wrapping mode
+
+        >>> t = Text("some words")
+        >>> t.render((6,)).text  # ... = b in Python 3
+        [...'some  ', ...'words ']
+        >>> t.set_wrap_mode("clip")
+        >>> t.wrap
+        'clip'
+        >>> t.render((6,)).text
+        [...'some w']
+        >>> t.wrap = "any"  # Urwid 0.9.9 or later
+        >>> t.render((6,)).text
+        [...'some w', ...'ords  ']
+        >>> t.wrap = "somehow"
+        Traceback (most recent call last):
+        TextError: Wrap mode 'somehow' not supported.
+        """
+        if not self.layout.supports_wrap_mode(mode):
+            raise TextError(f"Wrap mode {mode!r} not supported.")
+        self._wrap_mode = mode
+        self._invalidate()
+
+    def set_layout(
+        self,
+        align: Literal["left", "center", "right"] | Align,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode,
+        layout: text_layout.TextLayout | None = None,
+    ) -> None:
+        """
+        Set the text layout object, alignment and wrapping modes at
+        the same time.
+
+        :type align: text alignment mode
+        :param wrap: typically 'space', 'any', 'clip' or 'ellipsis'
+        :type wrap: text wrapping mode
+        :param layout: defaults to a shared :class:`StandardTextLayout` instance
+        :type layout: text layout instance
+
+        >>> t = Text("hi")
+        >>> t.set_layout("right", "clip")
+        >>> t
+        
+        """
+        if layout is None:
+            layout = text_layout.default_layout
+        self._layout = layout
+        self.set_align_mode(align)
+        self.set_wrap_mode(wrap)
+
+    align = property(lambda self: self._align_mode, set_align_mode)
+    wrap = property(lambda self: self._wrap_mode, set_wrap_mode)
+
+    @property
+    def layout(self):
+        return self._layout
+
+    def render(
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        focus: bool = False,
+    ) -> TextCanvas:
+        """
+        Render contents with wrapping and alignment.  Return canvas.
+
+        See :meth:`Widget.render` for parameter details.
+
+        >>> Text("important things").render((18,)).text
+        [b'important things  ']
+        >>> Text("important things").render((11,)).text
+        [b'important  ', b'things     ']
+        >>> Text("demo text").render(()).text
+        [b'demo text']
+        """
+        text, attr = self.get_text()
+        if size:
+            (maxcol,) = size
+        else:
+            maxcol, _ = self.pack(focus=focus)
+
+        trans = self.get_line_translation(maxcol, (text, attr))
+        return apply_text_layout(text, attr, trans, maxcol)
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        """
+        Return the number of rows the rendered text requires.
+
+        See :meth:`Widget.rows` for parameter details.
+
+        >>> Text("important things").rows((18,))
+        1
+        >>> Text("important things").rows((11,))
+        2
+        """
+        (maxcol,) = size
+        return len(self.get_line_translation(maxcol))
+
+    def get_line_translation(
+        self,
+        maxcol: int,
+        ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None = None,
+    ) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]:
+        """
+        Return layout structure used to map self.text to a canvas.
+        This method is used internally, but may be useful for debugging custom layout classes.
+
+        :param maxcol: columns available for display
+        :type maxcol: int
+        :param ta: ``None`` or the (*text*, *display attributes*) tuple
+                   returned from :meth:`.get_text`
+        :type ta: text and display attributes
+        """
+        if not self._cache_maxcol or self._cache_maxcol != maxcol:
+            self._update_cache_translation(maxcol, ta)
+        return self._cache_translation
+
+    def _update_cache_translation(
+        self,
+        maxcol: int,
+        ta: tuple[str | bytes, list[tuple[Hashable, int]]] | None,
+    ) -> None:
+        if ta:
+            text, _attr = ta
+        else:
+            text, _attr = self.get_text()
+        self._cache_maxcol = maxcol
+        self._cache_translation = self.layout.layout(text, maxcol, self._align_mode, self._wrap_mode)
+
+    def pack(
+        self,
+        size: tuple[()] | tuple[int] | None = None,  # type: ignore[override]
+        focus: bool = False,
+    ) -> tuple[int, int]:
+        """
+        Return the number of screen columns and rows required for
+        this Text widget to be displayed without wrapping or
+        clipping, as a single element tuple.
+
+        :param size: ``None`` or ``()`` for unlimited screen columns (like FIXED sizing)
+                     or (*maxcol*,) to specify a maximum column size
+        :type size: widget size
+        :param focus: widget is focused on
+        :type focus: bool
+
+        >>> Text("important things").pack()
+        (16, 1)
+        >>> Text("important things").pack((15,))
+        (9, 2)
+        >>> Text("important things").pack((8,))
+        (8, 2)
+        >>> Text("important things").pack(())
+        (16, 1)
+        >>> not_common_separated_text = "Line feed\\nLine Separator\\u2028Paragraph Separator\\u2029"
+        >>> # \u2028 (Line Separator) and \u2029 (Paragraph Separator) are not splitted by StandardTextLayout
+        >>> not_common_separated = Text(not_common_separated_text)
+
+        >>> not_common_separated.pack()
+        (33, 2)
+        >>> not_common_separated_canv = not_common_separated.render(())
+        >>> not_common_separated_canv.cols()
+        33
+        >>> not_common_separated_canv.rows()
+        2
+        """
+        text, attr = self.get_text()
+
+        if size:
+            (maxcol,) = size
+            if not hasattr(self.layout, "pack"):
+                return maxcol, self.rows(size, focus)
+
+            trans = self.get_line_translation(maxcol, (text, attr))
+            cols = self.layout.pack(maxcol, trans)
+            return (cols, len(trans))
+
+        if text:
+            if isinstance(text, bytes):
+                text = text.decode(get_encoding())
+
+            split_text = text.split("\n")
+
+            return (
+                max(calc_width(line, 0, len(line)) for line in split_text),
+                len(split_text),
+            )
+        return 0, 1
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/treetools.py b/python/user_packages/Python313/site-packages/urwid/widget/treetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb0234251db6b7d63b379b4b638e68ac9d38074c
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/treetools.py
@@ -0,0 +1,511 @@
+# Generic TreeWidget/TreeWalker class
+#    Copyright (c) 2010  Rob Lanphier
+#    Copyright (C) 2004-2010  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+"""
+Urwid tree view
+
+Features:
+- custom selectable widgets for trees
+- custom list walker for displaying widgets in a tree fashion
+"""
+
+from __future__ import annotations
+
+import typing
+
+from .columns import Columns
+from .constants import WHSettings
+from .listbox import ListBox, ListWalker
+from .padding import Padding
+from .text import Text
+from .widget import WidgetWrap
+from .wimp import SelectableIcon
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Hashable, Sequence
+
+__all__ = ("ParentNode", "TreeListBox", "TreeNode", "TreeWalker", "TreeWidget", "TreeWidgetError")
+
+
+class TreeWidgetError(RuntimeError):
+    pass
+
+
+class TreeWidget(WidgetWrap[Padding[typing.Union[Text, Columns]]]):
+    """A widget representing something in a nested tree display."""
+
+    indent_cols = 3
+    unexpanded_icon = SelectableIcon("+", 0)
+    expanded_icon = SelectableIcon("-", 0)
+
+    def __init__(self, node: TreeNode) -> None:
+        self._node = node
+        self._innerwidget: Text | None = None
+        self.is_leaf = not hasattr(node, "get_first_child")
+        self.expanded = True
+        widget = self.get_indented_widget()
+        super().__init__(widget)
+
+    def selectable(self) -> bool:
+        """
+        Allow selection of non-leaf nodes so children may be (un)expanded
+        """
+        return not self.is_leaf
+
+    def get_indented_widget(self) -> Padding[Text | Columns]:
+        widget = self.get_inner_widget()
+        if not self.is_leaf:
+            widget = Columns(
+                [(1, [self.unexpanded_icon, self.expanded_icon][self.expanded]), widget],
+                dividechars=1,
+            )
+        indent_cols = self.get_indent_cols()
+        return Padding(widget, width=(WHSettings.RELATIVE, 100), left=indent_cols)
+
+    def update_expanded_icon(self) -> None:
+        """Update display widget text for parent widgets"""
+        # icon is first element in columns indented widget
+        icon = [self.unexpanded_icon, self.expanded_icon][self.expanded]
+        self._w.base_widget.contents[0] = (icon, (WHSettings.GIVEN, 1, False))
+
+    def get_indent_cols(self) -> int:
+        return self.indent_cols * self.get_node().get_depth()
+
+    def get_inner_widget(self) -> Text:
+        if self._innerwidget is None:
+            self._innerwidget = self.load_inner_widget()
+        return self._innerwidget
+
+    def load_inner_widget(self) -> Text:
+        return Text(self.get_display_text())
+
+    def get_node(self) -> TreeNode:
+        return self._node
+
+    def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
+        return f"{self.get_node().get_key()}: {self.get_node().get_value()!s}"
+
+    def next_inorder(self) -> TreeWidget | None:
+        """Return the next TreeWidget depth first from this one."""
+        # first check if there's a child widget
+
+        if (first_child := self.first_child()) is not None:
+            return first_child
+
+        # now we need to hunt for the next sibling
+        this_node = self.get_node()
+        next_node = this_node.next_sibling()
+        depth = this_node.get_depth()
+        while next_node is None and depth > 0:
+            # keep going up the tree until we find an ancestor next sibling
+            this_node = this_node.get_parent()
+            next_node = this_node.next_sibling()
+            depth -= 1
+            if depth != this_node.get_depth():
+                raise ValueError(depth)
+        if next_node is None:
+            # we're at the end of the tree
+            return None
+
+        return next_node.get_widget()
+
+    def prev_inorder(self) -> TreeWidget | None:
+        """Return the previous TreeWidget depth first from this one."""
+        this_node = self._node
+
+        if (prev_node := this_node.prev_sibling()) is not None:
+            # we need to find the last child of the previous widget if its
+            # expanded
+            prev_widget = prev_node.get_widget()
+            if (last_child := prev_widget.last_child()) is not None:
+                return last_child
+
+            return prev_widget
+
+        # need to hunt for the parent
+        if this_node.get_depth() == 0:
+            return None
+
+        return this_node.get_parent().get_widget()
+
+    def keypress(
+        self,
+        size: tuple[int] | tuple[()],
+        key: str,
+    ) -> str | None:
+        """Handle expand & collapse requests (non-leaf nodes)"""
+        if self.is_leaf:
+            return key
+
+        if key in {"+", "right"}:
+            self.expanded = True
+            self.update_expanded_icon()
+            return None
+        if key == "-":
+            self.expanded = False
+            self.update_expanded_icon()
+            return None
+        if self._w.selectable():
+            return super().keypress(size, key)
+
+        return key
+
+    def mouse_event(
+        self,
+        size: tuple[int] | tuple[()],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool:
+        if self.is_leaf or event != "mouse press" or button != 1:
+            return False
+
+        if row == 0 and col == self.get_indent_cols():
+            self.expanded = not self.expanded
+            self.update_expanded_icon()
+            return True
+
+        return False
+
+    def first_child(self) -> TreeWidget | None:
+        """Return first child if expanded."""
+        if self.is_leaf or not self.expanded:
+            return None
+
+        if self._node.has_children():
+            first_node = self._node.get_first_child()
+            return first_node.get_widget()
+
+        return None
+
+    def last_child(self) -> TreeWidget | None:
+        """Return last child if expanded."""
+        if self.is_leaf or not self.expanded:
+            return None
+
+        if self._node.has_children():
+            last_child = self._node.get_last_child().get_widget()
+        else:
+            return None
+        # recursively search down for the last descendant
+        if (last_descendant := last_child.last_child()) is not None:
+            return last_descendant
+
+        return last_child
+
+
+class TreeNode:
+    """
+    Store tree contents and cache TreeWidget objects.
+    A TreeNode consists of the following elements:
+    *  key: accessor token for parent nodes
+    *  value: subclass-specific data
+    *  parent: a TreeNode which contains a pointer back to this object
+    *  widget: The widget used to render the object
+    """
+
+    def __init__(
+        self,
+        value: typing.Any,
+        parent: ParentNode | None = None,
+        key: Hashable | None = None,
+        depth: int | None = None,
+    ) -> None:
+        self._key = key
+        self._parent = parent
+        self._value = value
+        self._depth = depth
+        self._widget: TreeWidget | None = None
+
+    def get_widget(self, reload: bool = False) -> TreeWidget:
+        """Return the widget for this node."""
+        if self._widget is None or reload:
+            self._widget = self.load_widget()
+        return self._widget
+
+    def load_widget(self) -> TreeWidget:
+        return TreeWidget(self)
+
+    def get_depth(self) -> int:
+        if self._depth is self._parent is None:
+            self._depth = 0
+        elif self._depth is None:
+            self._depth = self._parent.get_depth() + 1
+        return self._depth
+
+    def get_index(self) -> int | None:
+        if self.get_depth() == 0:
+            return None
+
+        return self.get_parent().get_child_index(self.get_key())
+
+    def get_key(self) -> Hashable | None:
+        return self._key
+
+    def set_key(self, key: Hashable | None) -> None:
+        self._key = key
+
+    def change_key(self, key: Hashable | None) -> None:
+        self.get_parent().change_child_key(self._key, key)
+
+    def get_parent(self) -> ParentNode:
+        if self._parent is None and self.get_depth() > 0:
+            self._parent = self.load_parent()
+        return self._parent
+
+    def load_parent(self):
+        """Provide TreeNode with a parent for the current node.  This function
+        is only required if the tree was instantiated from a child node
+        (virtual function)"""
+        raise TreeWidgetError("virtual function.  Implement in subclass")
+
+    def get_value(self):
+        return self._value
+
+    def is_root(self) -> bool:
+        return self.get_depth() == 0
+
+    def next_sibling(self) -> TreeNode | None:
+        if self.get_depth() > 0:
+            return self.get_parent().next_child(self.get_key())
+
+        return None
+
+    def prev_sibling(self) -> TreeNode | None:
+        if self.get_depth() > 0:
+            return self.get_parent().prev_child(self.get_key())
+
+        return None
+
+    def get_root(self) -> ParentNode:
+        root = self
+        while root.get_parent() is not None:
+            root = root.get_parent()
+        return root
+
+
+class ParentNode(TreeNode):
+    """Maintain sort order for TreeNodes."""
+
+    def __init__(
+        self,
+        value: typing.Any,
+        parent: ParentNode | None = None,
+        key: Hashable = None,
+        depth: int | None = None,
+    ) -> None:
+        super().__init__(value, parent=parent, key=key, depth=depth)
+
+        self._child_keys: Sequence[Hashable] | None = None
+        self._children: dict[Hashable, TreeNode] = {}
+
+    def get_child_keys(self, reload: bool = False) -> Sequence[Hashable]:
+        """Return a possibly ordered list of child keys"""
+        if self._child_keys is None or reload:
+            self._child_keys = self.load_child_keys()
+        return self._child_keys
+
+    def load_child_keys(self) -> Sequence[Hashable]:
+        """Provide ParentNode with an ordered list of child keys (virtual function)"""
+        raise TreeWidgetError("virtual function.  Implement in subclass")
+
+    def get_child_widget(self, key) -> TreeWidget:
+        """Return the widget for a given key.  Create if necessary."""
+
+        return self.get_child_node(key).get_widget()
+
+    def get_child_node(self, key, reload: bool = False) -> TreeNode:
+        """Return the child node for a given key. Create if necessary."""
+        if key not in self._children or reload:
+            self._children[key] = self.load_child_node(key)
+        return self._children[key]
+
+    def load_child_node(self, key: Hashable) -> TreeNode:
+        """Load the child node for a given key (virtual function)"""
+        raise TreeWidgetError("virtual function.  Implement in subclass")
+
+    def set_child_node(self, key: Hashable, node: TreeNode) -> None:
+        """Set the child node for a given key.
+
+        Useful for bottom-up, lazy population of a tree.
+        """
+        self._children[key] = node
+
+    def change_child_key(self, oldkey: Hashable, newkey: Hashable) -> None:
+        if newkey in self._children:
+            raise TreeWidgetError(f"{newkey} is already in use")
+        self._children[newkey] = self._children.pop(oldkey)
+        self._children[newkey].set_key(newkey)
+
+    def get_child_index(self, key: Hashable) -> int:
+        try:
+            return self.get_child_keys().index(key)
+        except ValueError as exc:
+            raise TreeWidgetError(
+                f"Can't find key {key} in ParentNode {self.get_key()}\nParentNode items: {self.get_child_keys()!s}"
+            ).with_traceback(exc.__traceback__) from exc
+
+    def next_child(self, key: Hashable) -> TreeNode | None:
+        """Return the next child node in index order from the given key."""
+        if (index := self.get_child_index(key)) is not None and (index + 1) < len(child_keys := self.get_child_keys()):
+            # get the next item at same level
+            return self.get_child_node(child_keys[index + 1])
+
+        # the given node may have just been deleted
+        return None
+
+    def prev_child(self, key: Hashable) -> TreeNode | None:
+        """Return the previous child node in index order from the given key."""
+        if (index := self.get_child_index(key)) is not None and index >= 1:
+            # get the previous item at the same level
+            return self.get_child_node(self.get_child_keys()[index - 1])
+
+        return None
+
+    def get_first_child(self) -> TreeNode:
+        """Return the first TreeNode in the directory."""
+        child_keys = self.get_child_keys()
+        return self.get_child_node(child_keys[0])
+
+    def get_last_child(self) -> TreeNode:
+        """Return the last TreeNode in the directory."""
+        child_keys = self.get_child_keys()
+        return self.get_child_node(child_keys[-1])
+
+    def has_children(self) -> bool:
+        """Does this node have any children?"""
+        return len(self.get_child_keys()) > 0
+
+
+class TreeWalker(ListWalker):
+    """ListWalker-compatible class for displaying TreeWidgets
+
+    positions are TreeNodes."""
+
+    def __init__(self, start_from) -> None:
+        """start_from: TreeNode with the initial focus."""
+        self.focus = start_from
+
+    def get_focus(self):
+        widget = self.focus.get_widget()
+        return widget, self.focus
+
+    def set_focus(self, focus) -> None:
+        self.focus = focus
+        self._modified()
+
+    # pylint: disable=arguments-renamed  # its bad, but we should not change API
+    def get_next(self, start_from) -> tuple[TreeWidget, TreeNode] | tuple[None, None]:
+        if (target := start_from.get_widget().next_inorder()) is not None:
+            return target, target.get_node()
+
+        return None, None
+
+    def get_prev(self, start_from) -> tuple[TreeWidget, TreeNode] | tuple[None, None]:
+        if (target := start_from.get_widget().prev_inorder()) is not None:
+            return target, target.get_node()
+
+        return None, None
+
+    # pylint: enable=arguments-renamed
+
+
+class TreeListBox(ListBox):
+    """A ListBox with special handling for navigation and
+    collapsing of TreeWidgets"""
+
+    def keypress(
+        self,
+        size: tuple[int, int],  # type: ignore[override]
+        key: str,
+    ) -> str | None:
+        key: str | None = super().keypress(size, key)
+        return self.unhandled_input(size, key)
+
+    def unhandled_input(self, size: tuple[int, int], data: str) -> str | None:
+        """Handle macro-navigation keys"""
+        if data == "left":
+            self.move_focus_to_parent(size)
+            return None
+        if data == "-":
+            self.collapse_focus_parent(size)
+            return None
+
+        return data
+
+    def collapse_focus_parent(self, size: tuple[int, int]) -> None:
+        """Collapse parent directory."""
+
+        _widget, pos = self.body.get_focus()
+        self.move_focus_to_parent(size)
+
+        _pwidget, ppos = self.body.get_focus()
+        if pos != ppos:
+            self.keypress(size, "-")
+
+    def move_focus_to_parent(self, size: tuple[int, int]) -> None:
+        """Move focus to parent of widget in focus."""
+
+        _widget, pos = self.body.get_focus()
+
+        parentpos = pos.get_parent()
+
+        if parentpos is None:
+            return
+
+        middle, top, _bottom = self.calculate_visible(size)
+
+        row_offset, _focus_widget, _focus_pos, _focus_rows, _cursor = middle  # pylint: disable=unpacking-non-sequence
+        _trim_top, fill_above = top  # pylint: disable=unpacking-non-sequence
+
+        for _widget, pos, rows in fill_above:
+            row_offset -= rows
+            if pos == parentpos:
+                self.change_focus(size, pos, row_offset)
+                return
+
+        self.change_focus(size, pos.get_parent())
+
+    def _keypress_max_left(self, size: tuple[int, int]) -> None:
+        self.focus_home(size)
+
+    def _keypress_max_right(self, size: tuple[int, int]) -> None:
+        self.focus_end(size)
+
+    def focus_home(self, size: tuple[int, int]) -> None:
+        """Move focus to very top."""
+
+        _widget, pos = self.body.get_focus()
+        rootnode = pos.get_root()
+        self.change_focus(size, rootnode)
+
+    def focus_end(self, size: tuple[int, int]) -> None:
+        """Move focus to far bottom."""
+
+        maxrow, _maxcol = size
+        _widget, pos = self.body.get_focus()
+
+        if lastwidget := pos.get_root().get_widget().last_child():
+            lastnode = lastwidget.get_node()
+
+            self.change_focus(size, lastnode, maxrow - 1)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/widget.py b/python/user_packages/Python313/site-packages/urwid/widget/widget.py
new file mode 100644
index 0000000000000000000000000000000000000000..e90357f25effad473760da91649384307daedf05
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/widget.py
@@ -0,0 +1,728 @@
+# Urwid basic widget classes
+#    Copyright (C) 2004-2012  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+from __future__ import annotations
+
+import functools
+import logging
+import typing
+import warnings
+from operator import attrgetter
+
+from urwid import signals
+from urwid.canvas import Canvas, CanvasCache, CompositeCanvas
+from urwid.command_map import command_map
+from urwid.split_repr import split_repr
+from urwid.util import MetaSuper
+
+from .constants import Sizing
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Hashable
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+LOGGER = logging.getLogger(__name__)
+
+
+class WidgetMeta(signals.MetaSignals, MetaSuper):
+    """
+    Bases: :class:`MetaSuper`, :class:`MetaSignals`
+
+    Automatic caching of render and rows methods.
+
+    Class variable *no_cache* is a list of names of methods to not cache
+    automatically.  Valid method names for *no_cache* are ``'render'`` and
+    ``'rows'``.
+
+    Class variable *ignore_focus* if defined and set to ``True`` indicates
+    that the canvas this widget renders is not affected by the focus
+    parameter, so it may be ignored when caching.
+    """
+
+    def __init__(cls, name, bases, d):
+        no_cache = d.get("no_cache", [])
+
+        super().__init__(name, bases, d)
+
+        if "render" in d:
+            if "render" not in no_cache:
+                render_fn = cache_widget_render(cls)
+            else:
+                render_fn = nocache_widget_render(cls)
+            cls.render = render_fn
+
+        if "rows" in d and "rows" not in no_cache:
+            cls.rows = cache_widget_rows(cls)
+        if "no_cache" in d:
+            del cls.no_cache
+        if "ignore_focus" in d:
+            del cls.ignore_focus
+
+
+class WidgetError(Exception):
+    """Widget specific errors."""
+
+
+class WidgetWarning(Warning):
+    """Widget specific warnings."""
+
+
+def validate_size(widget, size, canv):
+    """
+    Raise a WidgetError if a canv does not match size.
+    """
+    if (size and size[1:] != (0,) and size[0] != canv.cols()) or (len(size) > 1 and size[1] != canv.rows()):
+        raise WidgetError(
+            f"Widget {widget!r} rendered ({canv.cols():d} x {canv.rows():d}) canvas when passed size {size!r}!"
+        )
+
+
+def cache_widget_render(cls):
+    """
+    Return a function that wraps the cls.render() method
+    and fetches and stores canvases with CanvasCache.
+    """
+    ignore_focus = bool(getattr(cls, "ignore_focus", False))
+    fn = cls.render
+
+    @functools.wraps(fn)
+    def cached_render(self, size, focus=False):
+        focus = focus and not ignore_focus
+
+        if canv := CanvasCache.fetch(self, cls, size, focus):
+            return canv
+
+        canv = fn(self, size, focus=focus)
+        validate_size(self, size, canv)
+        if canv.widget_info:
+            canv = CompositeCanvas(canv)
+        canv.finalize(self, size, focus)
+        CanvasCache.store(cls, canv)
+        return canv
+
+    cached_render.original_fn = fn
+    return cached_render
+
+
+def nocache_widget_render(cls):
+    """
+    Return a function that wraps the cls.render() method
+    and finalizes the canvas that it returns.
+    """
+    fn = cls.render
+    if hasattr(fn, "original_fn"):
+        fn = fn.original_fn
+
+    @functools.wraps(fn)
+    def finalize_render(self, size, focus=False):
+        canv = fn(self, size, focus=focus)
+        if canv.widget_info:
+            canv = CompositeCanvas(canv)
+        validate_size(self, size, canv)
+        canv.finalize(self, size, focus)
+        return canv
+
+    finalize_render.original_fn = fn
+    return finalize_render
+
+
+def nocache_widget_render_instance(self):
+    """
+    Return a function that wraps the cls.render() method
+    and finalizes the canvas that it returns, but does not
+    cache the canvas.
+    """
+    fn = self.render.original_fn
+
+    @functools.wraps(fn)
+    def finalize_render(size, focus=False):
+        canv = fn(self, size, focus=focus)
+        if canv.widget_info:
+            canv = CompositeCanvas(canv)
+        canv.finalize(self, size, focus)
+        return canv
+
+    finalize_render.original_fn = fn
+    return finalize_render
+
+
+def cache_widget_rows(cls):
+    """
+    Return a function that wraps the cls.rows() method
+    and returns rows from the CanvasCache if available.
+    """
+    ignore_focus = bool(getattr(cls, "ignore_focus", False))
+    fn = cls.rows
+
+    @functools.wraps(fn)
+    def cached_rows(self, size: tuple[int], focus: bool = False) -> int:
+        focus = focus and not ignore_focus
+
+        if canv := CanvasCache.fetch(self, cls, size, focus):
+            return canv.rows()
+
+        return fn(self, size, focus)
+
+    return cached_rows
+
+
+class Widget(metaclass=WidgetMeta):
+    """
+    Widget base class
+
+    .. attribute:: _selectable
+       :annotation: = False
+
+       The default :meth:`.selectable` method returns this value.
+
+    .. attribute:: _sizing
+       :annotation: = frozenset(['flow', 'box', 'fixed'])
+
+       The default :meth:`.sizing` method returns this value.
+
+    .. attribute:: _command_map
+       :annotation: = urwid.command_map
+
+       A shared :class:`CommandMap` instance. May be redefined in subclasses or widget instances.
+
+
+    .. method:: rows(size, focus=False)
+
+       .. note::
+
+          This method is not implemented in :class:`.Widget` but
+          must be implemented by any flow widget.  See :meth:`.sizing`.
+
+       See :meth:`Widget.render` for parameter details.
+
+       :returns: The number of rows required for this widget given a number of columns in *size*
+
+       This is the method flow widgets use to communicate their size to other
+       widgets without having to render a canvas. This should be a quick
+       calculation as this function may be called a number of times in normal
+       operation. If your implementation may take a long time you should add
+       your own caching here.
+
+       There is some metaclass magic defined in the :class:`Widget`
+       metaclass :class:`WidgetMeta` that causes the
+       result of this function to be retrieved from any
+       canvas cached by :class:`CanvasCache`, so if your widget
+       has been rendered you may not receive calls to this function. The class
+       variable :attr:`ignore_focus` may be defined and set to ``True`` if this
+       widget renders the same size regardless of the value of the *focus*
+       parameter.
+
+    .. method:: get_cursor_coords(size)
+
+       .. note::
+
+          This method is not implemented in :class:`.Widget` but
+          must be implemented by any widget that may return cursor
+          coordinates as part of the canvas that :meth:`render` returns.
+
+       :param size: See :meth:`Widget.render` for details.
+       :type size: widget size
+
+       :returns: (*col*, *row*) if this widget has a cursor, ``None`` otherwise
+
+       Return the cursor coordinates (*col*, *row*) of a cursor that will appear
+       as part of the canvas rendered by this widget when in focus, or ``None``
+       if no cursor is displayed.
+
+       The :class:`ListBox` widget
+       uses this method to make sure a cursor in the focus widget is not scrolled out of view.
+       It is a separate method to avoid having to render the whole widget while calculating layout.
+
+       Container widgets will typically call the :meth:`.get_cursor_coords` method on their focus widget.
+
+
+    .. method:: get_pref_col(size)
+
+       .. note::
+
+          This method is not implemented in :class:`.Widget` but may be implemented by a subclass.
+
+       :param size: See :meth:`Widget.render` for details.
+       :type size: widget size
+
+       :returns: a column number or ``'left'`` for the leftmost available
+                 column or ``'right'`` for the rightmost available column
+
+       Return the preferred column for the cursor to be displayed in this
+       widget. This value might not be the same as the column returned from
+       :meth:`get_cursor_coords`.
+
+       The :class:`ListBox` and :class:`Pile`
+       widgets call this method on a widget losing focus and use the value
+       returned to call :meth:`.move_cursor_to_coords` on the widget becoming
+       the focus. This allows the focus to move up and down through widgets
+       while keeping the cursor in approximately the same column on screen.
+
+
+    .. method:: move_cursor_to_coords(size, col, row)
+
+       .. note::
+
+          This method is not implemented in :class:`.Widget` but may be implemented by a subclass.
+          Not implementing this method is equivalent to having a method that always returns
+          ``False``.
+
+       :param size: See :meth:`Widget.render` for details.
+       :type size: widget size
+       :param col: new column for the cursor, 0 is the left edge of this widget
+       :type col: int
+       :param row: new row for the cursor, 0 it the top row of this widget
+       :type row: int
+
+       :returns: ``True`` if the position was set successfully anywhere on *row*, ``False`` otherwise
+    """
+
+    _selectable = False
+    _sizing = frozenset([Sizing.FLOW, Sizing.BOX, Sizing.FIXED])
+    _command_map = command_map
+
+    def __init__(self) -> None:
+        self.logger = logging.getLogger(f"{self.__class__.__module__}.{self.__class__.__name__}")
+
+    def _invalidate(self) -> None:
+        """Mark cached canvases rendered by this widget as dirty so that they will not be used again."""
+        CanvasCache.invalidate(self)
+
+    def _emit(self, name: Hashable, *args) -> None:
+        """Convenience function to emit signals with self as first argument."""
+        signals.emit_signal(self, name, self, *args)
+
+    def selectable(self) -> bool:
+        """
+        :returns: ``True`` if this is a widget that is designed to take the
+                  focus, i.e. it contains something the user might want to
+                  interact with, ``False`` otherwise,
+
+        This default implementation returns :attr:`._selectable`.
+        Subclasses may leave these is if the are not selectable,
+        or if they are always selectable they may
+        set the :attr:`_selectable` class variable to ``True``.
+
+        If this method returns ``True`` then the :meth:`.keypress` method
+        must be implemented.
+
+        Returning ``False`` does not guarantee that this widget will never be in
+        focus, only that this widget will usually be skipped over when changing
+        focus. It is still possible for non selectable widgets to have the focus
+        (typically when there are no other selectable widgets visible).
+        """
+        return self._selectable
+
+    def sizing(self) -> frozenset[Sizing]:
+        """
+        :returns: A frozenset including one or more of ``'box'``, ``'flow'`` and
+                  ``'fixed'``.  Default implementation returns the value of
+                  :attr:`._sizing`, which for this class includes all three.
+
+        The sizing modes returned indicate the modes that may be
+        supported by this widget, but is not sufficient to know
+        that using that sizing mode will work.  Subclasses should
+        make an effort to remove sizing modes they know will not
+        work given the state of the widget, but many do not yet
+        do this.
+
+        If a sizing mode is missing from the set then the widget
+        should fail when used in that mode.
+
+        If ``'flow'`` is among the values returned then the other
+        methods in this widget must be able to accept a
+        single-element tuple (*maxcol*,) to their ``size``
+        parameter, and the :meth:`rows` method must be defined.
+
+        If ``'box'`` is among the values returned then the other
+        methods must be able to accept a two-element tuple
+        (*maxcol*, *maxrow*) to their size parameter.
+
+        If ``'fixed'`` is among the values returned then the other
+        methods must be able to accept an empty tuple () to
+        their size parameter, and the :meth:`pack` method must
+        be defined.
+        """
+        return self._sizing
+
+    def pack(self, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool = False) -> tuple[int, int]:
+        """
+        See :meth:`Widget.render` for parameter details.
+
+        :returns: A "packed" size (*maxcol*, *maxrow*) for this widget
+
+        Calculate and return a minimum
+        size where all content could still be displayed. Fixed widgets must
+        implement this method and return their size when ``()`` is passed as the
+        *size* parameter.
+
+        This default implementation returns the *size* passed, or the *maxcol*
+        passed and the value of :meth:`rows` as the *maxrow* when (*maxcol*,)
+        is passed as the *size* parameter.
+
+        .. note::
+
+           This is a new method that hasn't been fully implemented across the
+           standard widget types. In particular it has not yet been
+           implemented for container widgets.
+
+        :class:`Text` widgets have implemented this method.
+        You can use :meth:`Text.pack` to calculate the minimum
+        columns and rows required to display a text widget without wrapping,
+        or call it iteratively to calculate the minimum number of columns
+        required to display the text wrapped into a target number of rows.
+        """
+        if not size:
+            if Sizing.FIXED in self.sizing():
+                raise NotImplementedError(f"{self!r} must override Widget.pack()")
+            raise WidgetError(f"Cannot pack () size, this is not a fixed widget: {self!r}")
+
+        if len(size) == 1:
+            if Sizing.FLOW in self.sizing():
+                return (*size, self.rows(size, focus))  # pylint: disable=no-member  # can not announce abstract
+
+            raise WidgetError(f"Cannot pack (maxcol,) size, this is not a flow widget: {self!r}")
+
+        return size
+
+    @property
+    def base_widget(self) -> Widget:
+        """Read-only property that steps through decoration widgets and returns the one at the base.
+
+        This default implementation returns self.
+        """
+        return self
+
+    @property
+    def focus(self) -> Widget | None:
+        """
+        Read-only property returning the child widget in focus for container widgets.
+
+        This default implementation always returns ``None``, indicating that this widget has no children.
+        """
+        return None
+
+    def _not_a_container(self, val=None):
+        raise IndexError(f"No focus_position, {self!r} is not a container widget")
+
+    focus_position = property(
+        _not_a_container,
+        _not_a_container,
+        doc="""
+        Property for reading and setting the focus position for
+        container widgets. This default implementation raises
+        :exc:`IndexError`, making normal widgets fail the same way
+        accessing :attr:`.focus_position` on an empty container widget would.
+        """,
+    )
+
+    def __repr__(self):
+        """A friendly __repr__ for widgets.
+
+        Designed to be extended by subclasses with _repr_words and _repr_attr methods.
+        """
+        return split_repr(self)
+
+    def _repr_words(self) -> list[str]:
+        words = []
+        if self.selectable():
+            words = ["selectable", *words]
+        if self.sizing() and self.sizing() != frozenset([Sizing.FLOW, Sizing.BOX, Sizing.FIXED]):
+            words.append("/".join(sorted(self.sizing())))
+        return [*words, "widget"]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        return {}
+
+    def keypress(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        key: str,
+    ) -> str | None:
+        """Keyboard input handler.
+
+        :param size: See :meth:`Widget.render` for details
+        :type size: tuple[()] | tuple[int] | tuple[int, int]
+        :param key: a single keystroke value; see :ref:`keyboard-input`
+        :type key: str
+        :return: ``None`` if *key* was handled by *key* (the same value passed) if *key* was not handled
+        :rtype: str | None
+        """
+        if not self.selectable():
+            if hasattr(self, "logger"):
+                self.logger.debug(f"keypress sent to non selectable widget {self!r}")
+            else:
+                warnings.warn(
+                    f"Widget {self.__class__.__name__} did not call 'super().__init__()",
+                    WidgetWarning,
+                    stacklevel=3,
+                )
+                LOGGER.debug(f"Widget {self!r} is not selectable")
+        return key
+
+    def mouse_event(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        event: str,
+        button: int,
+        col: int,
+        row: int,
+        focus: bool,
+    ) -> bool | None:
+        """Mouse event handler.
+
+        :param size: See :meth:`Widget.render` for details.
+        :type size: tuple[()] | tuple[int] | tuple[int, int]
+        :param event: Values such as ``'mouse press'``, ``'ctrl mouse press'``,
+                     ``'mouse release'``, ``'meta mouse release'``,
+                     ``'mouse drag'``; see :ref:`mouse-input`
+        :type event: str
+        :param button: 1 through 5 for press events, often 0 for release events
+                      (which button was released is often not known)
+        :type button: int
+        :param col: Column of the event, 0 is the left edge of this widget
+        :type col: int
+        :param row: Row of the event, 0 it the top row of this widget
+        :type row: int
+        :param focus: Set to ``True`` if this widget or one of its children is in focus
+        :type focus: bool
+        :return: ``True`` if the event was handled by this widget, ``False`` otherwise
+        :rtype: bool | None
+        """
+        if not self.selectable():
+            if hasattr(self, "logger"):
+                self.logger.debug(f"Widget {self!r} is not selectable")
+            else:
+                warnings.warn(
+                    f"Widget {self.__class__.__name__} not called 'super().__init__()",
+                    WidgetWarning,
+                    stacklevel=3,
+                )
+                LOGGER.debug(f"Widget {self!r} is not selectable")
+        return False
+
+    def render(
+        self,
+        size: tuple[()] | tuple[int] | tuple[int, int],
+        focus: bool = False,
+    ) -> Canvas:
+        """Render widget and produce canvas
+
+        :param size: One of the following, *maxcol* and *maxrow* are integers > 0:
+
+            (*maxcol*, *maxrow*)
+              for box sizing -- the parent chooses the exact
+              size of this widget
+
+            (*maxcol*,)
+              for flow sizing -- the parent chooses only the
+              number of columns for this widget
+
+            ()
+              for fixed sizing -- this widget is a fixed size
+              which can't be adjusted by the parent
+        :type size: widget size
+        :param focus: set to ``True`` if this widget or one of its children is in focus
+        :type focus: bool
+
+        :returns: A :class:`Canvas` subclass instance containing the rendered content of this widget
+
+        :class:`Text` widgets return a :class:`TextCanvas` (arbitrary text and display attributes),
+        :class:`SolidFill` widgets return a :class:`SolidCanvas` (a single character repeated across the whole surface)
+        and container widgets return a :class:`CompositeCanvas` (one or more other canvases arranged arbitrarily).
+
+        If *focus* is ``False``, the returned canvas may not have a cursor position set.
+
+        There is some metaclass magic defined in the :class:`Widget` metaclass :class:`WidgetMeta`
+        that causes the result of this method to be cached by :class:`CanvasCache`.
+        Later calls will automatically look up the value in the cache first.
+
+        As a small optimization the class variable :attr:`ignore_focus`
+        may be defined and set to ``True`` if this widget renders the same
+        canvas regardless of the value of the *focus* parameter.
+
+        Any time the content of a widget changes it should call
+        :meth:`_invalidate` to remove any cached canvases, or the widget
+        may render the cached canvas instead of creating a new one.
+        """
+        raise NotImplementedError
+
+
+def fixed_size(size: tuple[()]) -> None:
+    """
+    raise ValueError if size != ().
+
+    Used by FixedWidgets to test size parameter.
+    """
+    if size:
+        raise ValueError(f"FixedWidget takes only () for size.passed: {size!r}")
+
+
+def delegate_to_widget_mixin(attribute_name: str) -> type[Widget]:
+    """
+    Return a mixin class that delegates all standard widget methods
+    to an attribute given by attribute_name.
+
+    This mixin is designed to be used as a superclass of another widget.
+    """
+    # FIXME: this is so common, let's add proper support for it
+    # when layout and rendering are separated
+
+    get_delegate = attrgetter(attribute_name)
+
+    class DelegateToWidgetMixin(Widget):
+        no_cache: typing.ClassVar[list[str]] = ["rows"]  # crufty metaclass work-around
+
+        def render(self, size, focus: bool = False) -> CompositeCanvas:
+            canv = get_delegate(self).render(size, focus=focus)
+            return CompositeCanvas(canv)
+
+        @property
+        def selectable(self) -> Callable[[], bool]:
+            return get_delegate(self).selectable
+
+        @property
+        def get_cursor_coords(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int]], tuple[int, int] | None]:
+            # TODO(Aleksei):  Get rid of property usage after getting rid of "if getattr"
+            return get_delegate(self).get_cursor_coords
+
+        @property
+        def get_pref_col(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int]], int | None]:
+            # TODO(Aleksei):  Get rid of property usage after getting rid of "if getattr"
+            return get_delegate(self).get_pref_col
+
+        def keypress(self, size: tuple[()] | tuple[int] | tuple[int, int], key: str) -> str | None:
+            return get_delegate(self).keypress(size, key)
+
+        @property
+        def move_cursor_to_coords(self) -> Callable[[[tuple[()] | tuple[int] | tuple[int, int], int, int]], bool]:
+            # TODO(Aleksei):  Get rid of property usage after getting rid of "if getattr"
+            return get_delegate(self).move_cursor_to_coords
+
+        @property
+        def rows(self) -> Callable[[tuple[int], bool], int]:
+            return get_delegate(self).rows
+
+        @property
+        def mouse_event(
+            self,
+        ) -> Callable[[tuple[()] | tuple[int] | tuple[int, int], str, int, int, int, bool], bool | None]:
+            # TODO(Aleksei):  Get rid of property usage after getting rid of "if getattr"
+            return get_delegate(self).mouse_event
+
+        @property
+        def sizing(self) -> Callable[[], frozenset[Sizing]]:
+            return get_delegate(self).sizing
+
+        @property
+        def pack(self) -> Callable[[tuple[()] | tuple[int] | tuple[int, int], bool], tuple[int, int]]:
+            return get_delegate(self).pack
+
+    return DelegateToWidgetMixin
+
+
+class WidgetWrapError(Exception):
+    pass
+
+
+class WidgetWrap(delegate_to_widget_mixin("_wrapped_widget"), typing.Generic[WrappedWidget]):
+    def __init__(self, w: WrappedWidget) -> None:
+        """
+        w -- widget to wrap, stored as self._w
+
+        This object will pass the functions defined in Widget interface
+        definition to self._w.
+
+        The purpose of this widget is to provide a base class for
+        widgets that compose other widgets for their display and
+        behaviour.  The details of that composition should not affect
+        users of the subclass.  The subclass may decide to expose some
+        of the wrapped widgets by behaving like a ContainerWidget or
+        WidgetDecoration, or it may hide them from outside access.
+        """
+        super().__init__()
+        if not isinstance(w, Widget):
+            obj_class_path = f"{w.__class__.__module__}.{w.__class__.__name__}"
+            warnings.warn(
+                f"{obj_class_path} is not subclass of Widget",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        self._wrapped_widget = w
+
+    @property
+    def _w(self) -> WrappedWidget:
+        return self._wrapped_widget
+
+    @_w.setter
+    def _w(self, new_widget: WrappedWidget) -> None:
+        """
+        Change the wrapped widget.  This is meant to be called
+        only by subclasses.
+
+        >>> size = (10,)
+        >>> ww = WidgetWrap(Edit("hello? ", "hi"))
+        >>> ww.render(size).text  # ... = b in Python 3
+        [...'hello? hi ']
+        >>> ww.selectable()
+        True
+        >>> ww._w = Text("goodbye")  # calls _set_w()
+        >>> ww.render(size).text
+        [...'goodbye   ']
+        >>> ww.selectable()
+        False
+        """
+        self._wrapped_widget = new_widget
+        self._invalidate()
+
+    def _set_w(self, w: WrappedWidget) -> None:
+        """
+        Change the wrapped widget.  This is meant to be called
+        only by subclasses.
+        >>> from urwid import Edit, Text
+        >>> size = (10,)
+        >>> ww = WidgetWrap(Edit("hello? ", "hi"))
+        >>> ww.render(size).text  # ... = b in Python 3
+        [...'hello? hi ']
+        >>> ww.selectable()
+        True
+        >>> ww._w = Text("goodbye")  # calls _set_w()
+        >>> ww.render(size).text
+        [...'goodbye   ']
+        >>> ww.selectable()
+        False
+        """
+        warnings.warn(
+            "_set_w is deprecated. Please use 'WidgetWrap._w' property directly. API will be removed in version 5.0.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self._wrapped_widget = w
+        self._invalidate()
+
+
+def _test():
+    import doctest
+
+    doctest.testmod()
+
+
+if __name__ == "__main__":
+    _test()
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/widget_decoration.py b/python/user_packages/Python313/site-packages/urwid/widget/widget_decoration.py
new file mode 100644
index 0000000000000000000000000000000000000000..22775d1bffa1e8acca5872618469a967aab994b5
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/widget_decoration.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+import typing
+import warnings
+
+from urwid.canvas import CompositeCanvas
+
+from .widget import Widget, WidgetError, WidgetWarning, delegate_to_widget_mixin
+
+if typing.TYPE_CHECKING:
+    from typing_extensions import Literal
+
+    from .constants import Sizing
+
+
+__all__ = (
+    "WidgetDecoration",
+    "WidgetDisable",
+    "WidgetError",
+    "WidgetPlaceholder",
+    "WidgetWarning",
+    "delegate_to_widget_mixin",
+)
+
+WrappedWidget = typing.TypeVar("WrappedWidget")
+
+
+class WidgetDecoration(Widget, typing.Generic[WrappedWidget]):  # pylint: disable=abstract-method
+    """
+    original_widget -- the widget being decorated
+
+    This is a base class for decoration widgets,
+    widgets that contain one or more widgets and only ever have a single focus.
+    This type of widget will affect the display or behaviour of the original_widget,
+    but it is not part of determining a chain of focus.
+
+    Don't actually do this -- use a WidgetDecoration subclass instead, these are not real widgets:
+
+    >>> from urwid import Text
+    >>> WidgetDecoration(Text("hi"))
+    >
+
+    .. Warning:
+        WidgetDecoration do not implement ``render`` method.
+        Implement it or forward to the widget in the subclass.
+    """
+
+    def __init__(self, original_widget: WrappedWidget) -> None:
+        # TODO(Aleksei): reduce amount of multiple inheritance usage
+        # Special case: subclasses with multiple inheritance causes `super` call wrong way
+        # Call parent __init__ explicit
+        Widget.__init__(self)
+        if not isinstance(original_widget, Widget):
+            obj_class_path = f"{original_widget.__class__.__module__}.{original_widget.__class__.__name__}"
+            warnings.warn(
+                f"{obj_class_path} is not subclass of Widget",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+        self._original_widget = original_widget
+
+    def _repr_words(self) -> list[str]:
+        return [*super()._repr_words(), repr(self._original_widget)]
+
+    @property
+    def original_widget(self) -> WrappedWidget:
+        return self._original_widget
+
+    @original_widget.setter
+    def original_widget(self, original_widget: WrappedWidget) -> None:
+        self._original_widget = original_widget
+        self._invalidate()
+
+    @property
+    def base_widget(self) -> Widget:
+        """
+        Return the widget without decorations.
+
+        If there is only one Decoration, then this is the same as original_widget.
+
+        >>> from urwid import Text
+        >>> t = Text("hello")
+        >>> wd1 = WidgetDecoration(t)
+        >>> wd2 = WidgetDecoration(wd1)
+        >>> wd3 = WidgetDecoration(wd2)
+        >>> wd3.original_widget is wd2
+        True
+        >>> wd3.base_widget is t
+        True
+        """
+        visited = {self}
+        w = self
+        while (w := getattr(w, "_original_widget", w)) not in visited:
+            visited.add(w)
+        return w
+
+    def selectable(self) -> bool:
+        return self._original_widget.selectable()
+
+    def sizing(self) -> frozenset[Sizing]:
+        return self._original_widget.sizing()
+
+
+class WidgetPlaceholder(delegate_to_widget_mixin("_original_widget"), WidgetDecoration[WrappedWidget]):
+    """
+    This is a do-nothing decoration widget that can be used for swapping
+    between widgets without modifying the container of this widget.
+
+    This can be useful for making an interface with a number of distinct
+    pages or for showing and hiding menu or status bars.
+
+    The widget displayed is stored as the self.original_widget property and
+    can be changed by assigning a new widget to it.
+    """
+
+
+class WidgetDisable(WidgetDecoration[WrappedWidget]):
+    """
+    A decoration widget that disables interaction with the widget it
+    wraps.  This widget always passes focus=False to the wrapped widget,
+    even if it somehow does become the focus.
+    """
+
+    no_cache: typing.ClassVar[list[str]] = ["rows"]
+    ignore_focus = True
+
+    def selectable(self) -> Literal[False]:
+        return False
+
+    def rows(self, size: tuple[int], focus: bool = False) -> int:
+        return self._original_widget.rows(size, False)
+
+    def sizing(self) -> frozenset[Sizing]:
+        return self._original_widget.sizing()
+
+    def pack(self, size, focus: bool = False) -> tuple[int, int]:
+        return self._original_widget.pack(size, False)
+
+    def render(self, size, focus: bool = False) -> CompositeCanvas:
+        canv = self._original_widget.render(size, False)
+        return CompositeCanvas(canv)
diff --git a/python/user_packages/Python313/site-packages/urwid/widget/wimp.py b/python/user_packages/Python313/site-packages/urwid/widget/wimp.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d058c32d7b96f1a1a7c26b5a52242b69930c4f8
--- /dev/null
+++ b/python/user_packages/Python313/site-packages/urwid/widget/wimp.py
@@ -0,0 +1,796 @@
+# Urwid Window-Icon-Menu-Pointer-style widget classes
+#    Copyright (C) 2004-2011  Ian Ward
+#
+#    This library is free software; you can redistribute it and/or
+#    modify it under the terms of the GNU Lesser General Public
+#    License as published by the Free Software Foundation; either
+#    version 2.1 of the License, or (at your option) any later version.
+#
+#    This library is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+#    Lesser General Public License for more details.
+#
+#    You should have received a copy of the GNU Lesser General Public
+#    License along with this library; if not, write to the Free Software
+#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+#
+# Urwid web site: https://urwid.org/
+
+
+from __future__ import annotations
+
+import typing
+
+from urwid.canvas import CompositeCanvas
+from urwid.command_map import Command
+from urwid.signals import connect_signal
+from urwid.text_layout import calc_coords
+from urwid.util import is_mouse_press
+
+from .columns import Columns
+from .constants import Align, WrapMode
+from .text import Text
+from .widget import WidgetError, WidgetWrap
+
+if typing.TYPE_CHECKING:
+    from collections.abc import Callable, Hashable, MutableSequence
+
+    from typing_extensions import Literal, Self
+
+    from urwid.canvas import TextCanvas
+    from urwid.text_layout import TextLayout
+
+    _T = typing.TypeVar("_T")
+
+
+class SelectableIcon(Text):
+    ignore_focus = False
+    _selectable = True
+
+    def __init__(
+        self,
+        text: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        cursor_position: int = 0,
+        align: Literal["left", "center", "right"] | Align = Align.LEFT,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE,
+        layout: TextLayout | None = None,
+    ) -> None:
+        """
+        :param text: markup for this widget; see :class:`Text` for
+                     description of text markup
+        :param cursor_position: position the cursor will appear in the
+                                text when this widget is in focus
+        :param align: typically ``'left'``, ``'center'`` or ``'right'``
+        :type align: text alignment mode
+        :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'``
+        :type wrap: text wrapping mode
+        :param layout: defaults to a shared :class:`StandardTextLayout` instance
+        :type layout: text layout instance
+
+        This is a text widget that is selectable.  A cursor
+        displayed at a fixed location in the text when in focus.
+        This widget has no special handling of keyboard or mouse input.
+        """
+        super().__init__(text, align=align, wrap=wrap, layout=layout)
+        self._cursor_position = cursor_position
+
+    def render(  # type: ignore[override]
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        focus: bool = False,
+    ) -> TextCanvas | CompositeCanvas:  # type: ignore[override]
+        """
+        Render the text content of this widget with a cursor when
+        in focus.
+
+        >>> si = SelectableIcon("[!]")
+        >>> si
+        
+        >>> si.render((4,), focus=True).cursor
+        (0, 0)
+        >>> si = SelectableIcon("((*))", 2)
+        >>> si.render((8,), focus=True).cursor
+        (2, 0)
+        >>> si.render((2,), focus=True).cursor
+        (0, 1)
+        >>> si.render(()).cursor
+        >>> si.render(()).text
+        [b'((*))']
+        >>> si.render((), focus=True).cursor
+        (2, 0)
+        """
+        c: TextCanvas | CompositeCanvas = super().render(size, focus)
+        if focus:
+            # create a new canvas so we can add a cursor
+            c = CompositeCanvas(c)
+            c.cursor = self.get_cursor_coords(size)
+        return c
+
+    def get_cursor_coords(self, size: tuple[int] | tuple[()]) -> tuple[int, int] | None:
+        """
+        Return the position of the cursor if visible.  This method
+        is required for widgets that display a cursor.
+        """
+        if self._cursor_position > len(self.text):
+            return None
+        # find out where the cursor will be displayed based on
+        # the text layout
+        if size:
+            (maxcol,) = size
+        else:
+            maxcol, _ = self.pack()
+        trans = self.get_line_translation(maxcol)
+        x, y = calc_coords(self.text, trans, self._cursor_position)
+        if maxcol <= x:
+            return None
+        return x, y
+
+    def keypress(
+        self,
+        size: tuple[int] | tuple[()],  # type: ignore[override]
+        key: str,
+    ) -> str:
+        """
+        No keys are handled by this widget.  This method is
+        required for selectable widgets.
+        """
+        return key
+
+
+class CheckBoxError(WidgetError):
+    pass
+
+
+class CheckBox(WidgetWrap[Columns]):
+    states: typing.ClassVar[dict[bool | Literal["mixed"], SelectableIcon]] = {
+        True: SelectableIcon("[X]", 1),
+        False: SelectableIcon("[ ]", 1),
+        "mixed": SelectableIcon("[#]", 1),
+    }
+    reserve_columns = 4
+
+    # allow users of this class to listen for change events
+    # sent when the state of this widget is modified
+    # (this variable is picked up by the MetaSignals metaclass)
+    signals: typing.ClassVar[list[str]] = ["change", "postchange"]
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool = False,
+        has_mixed: typing.Literal[False] = False,
+        on_state_change: Callable[[Self, bool, _T], typing.Any] | None = None,
+        user_data: _T = ...,
+        checked_symbol: str | None = ...,
+    ) -> None: ...
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: typing.Literal["mixed"] | bool = False,
+        has_mixed: typing.Literal[True] = True,
+        on_state_change: Callable[[Self, bool | typing.Literal["mixed"], _T], typing.Any] | None = None,
+        user_data: _T = ...,
+        checked_symbol: str | None = ...,
+    ) -> None: ...
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool = False,
+        has_mixed: typing.Literal[False] = False,
+        on_state_change: Callable[[Self, bool], typing.Any] | None = None,
+        user_data: None = None,
+        checked_symbol: str | None = ...,
+    ) -> None: ...
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: typing.Literal["mixed"] | bool = False,
+        has_mixed: typing.Literal[True] = True,
+        on_state_change: Callable[[Self, bool | typing.Literal["mixed"]], typing.Any] | None = None,
+        user_data: None = None,
+        checked_symbol: str | None = ...,
+    ) -> None: ...
+
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool | Literal["mixed"] = False,
+        has_mixed: typing.Literal[False, True] = False,  # MyPy issue: Literal[True, False] is not equal `bool`
+        on_state_change: (
+            Callable[[Self, bool, _T], typing.Any]
+            | Callable[[Self, bool | typing.Literal["mixed"], _T], typing.Any]
+            | Callable[[Self, bool], typing.Any]
+            | Callable[[Self, bool | typing.Literal["mixed"]], typing.Any]
+            | None
+        ) = None,
+        user_data: _T | None = None,
+        checked_symbol: str | None = None,
+    ):
+        """
+        :param label: markup for check box label
+        :param state: False, True or "mixed"
+        :param has_mixed: True if "mixed" is a state to cycle through
+        :param on_state_change: shorthand for connect_signal()
+                                function call for a single callback
+        :param user_data: user_data for on_state_change
+
+        ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside
+
+        Signals supported: ``'change'``, ``"postchange"``
+
+        Register signal handler with::
+
+          urwid.connect_signal(check_box, "change", callback, user_data)
+
+        where callback is callback(check_box, new_state [,user_data])
+        Unregister signal handlers with::
+
+          urwid.disconnect_signal(check_box, "change", callback, user_data)
+
+        >>> CheckBox("Confirm")
+        
+        >>> CheckBox("Yogourt", "mixed", True)
+        
+        >>> cb = CheckBox("Extra onions", True)
+        >>> cb
+        
+        >>> cb.render((20,), focus=True).text
+        [b'[X] Extra onions    ']
+        >>> CheckBox("Test", None)
+        Traceback (most recent call last):
+        ...
+        ValueError: None not in (True, False, 'mixed')
+        """
+        if state not in self.states:
+            raise ValueError(f"{state!r} not in {tuple(self.states.keys())}")
+
+        self._label = Text(label)
+        self.has_mixed = has_mixed
+
+        self._state = state
+        if checked_symbol:
+            self.states[True] = SelectableIcon(f"[{checked_symbol}]", 1)
+        # The old way of listening for a change was to pass the callback
+        # in to the constructor.  Just convert it to the new way:
+        if on_state_change:
+            connect_signal(self, "change", on_state_change, user_data)
+
+        # Initial create expect no callbacks call, create explicit
+        super().__init__(
+            Columns(
+                [(self.reserve_columns, self.states[state]), self._label],
+                focus_column=0,
+            ),
+        )
+
+    def pack(self, size: tuple[()] | tuple[int] | None = None, focus: bool = False) -> tuple[str, str]:
+        """Pack for widget.
+
+        :param size: size data. Special case: None - get minimal widget size to fit
+        :param focus: widget is focused
+
+        >>> cb = CheckBox("test")
+        >>> cb.pack((10,))
+        (10, 1)
+        >>> cb.pack()
+        (8, 1)
+        >>> ml_cb = CheckBox("Multi\\nline\\ncheckbox")
+        >>> ml_cb.pack()
+        (12, 3)
+        >>> ml_cb.pack((), True)
+        (12, 3)
+        """
+        return super().pack(size or (), focus)
+
+    def _repr_words(self) -> list[str]:
+        return [*super()._repr_words(), repr(self.label)]
+
+    def _repr_attrs(self) -> dict[str, typing.Any]:
+        return {**super()._repr_attrs(), "state": self.state}
+
+    def set_label(self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]):
+        """
+        Change the check box label.
+
+        label -- markup for label.  See Text widget for description
+        of text markup.
+
+        >>> cb = CheckBox("foo")
+        >>> cb
+        
+        >>> cb.set_label(("bright_attr", "bar"))
+        >>> cb
+        
+        """
+        self._label.set_text(label)
+        # no need to call self._invalidate(). WidgetWrap takes care of
+        # that when self.w changes
+
+    def get_label(self):
+        """
+        Return label text.
+
+        >>> cb = CheckBox("Seriously")
+        >>> print(cb.get_label())
+        Seriously
+        >>> print(cb.label)
+        Seriously
+        >>> cb.set_label([("bright_attr", "flashy"), " normal"])
+        >>> print(cb.label)  #  only text is returned
+        flashy normal
+        """
+        return self._label.text
+
+    label = property(get_label)
+
+    def set_state(
+        self,
+        state: bool | Literal["mixed"],
+        do_callback: bool = True,
+    ) -> None:
+        """
+        Set the CheckBox state.
+
+        state -- True, False or "mixed"
+        do_callback -- False to suppress signal from this change
+
+        >>> from urwid import disconnect_signal
+        >>> changes = []
+        >>> def callback_a(user_data, cb, state):
+        ...     changes.append("A %r %r" % (state, user_data))
+        >>> def callback_b(cb, state):
+        ...     changes.append("B %r" % state)
+        >>> cb = CheckBox("test", False, False)
+        >>> key1 = connect_signal(cb, "change", callback_a, user_args=("user_a",))
+        >>> key2 = connect_signal(cb, "change", callback_b)
+        >>> cb.set_state(True)  # both callbacks will be triggered
+        >>> cb.state
+        True
+        >>> disconnect_signal(cb, "change", callback_a, user_args=("user_a",))
+        >>> cb.state = False
+        >>> cb.state
+        False
+        >>> cb.set_state(True)
+        >>> cb.state
+        True
+        >>> cb.set_state(False, False)  # don't send signal
+        >>> changes
+        ["A True 'user_a'", 'B True', 'B False', 'B True']
+        """
+        if self._state == state:
+            return
+
+        if state not in self.states:
+            raise CheckBoxError(f"{self!r} Invalid state: {state!r}")
+
+        # self._state is None is a special case when the CheckBox
+        # has just been created
+        old_state = self._state
+        if do_callback:
+            self._emit("change", state)
+        self._state = state
+        # rebuild the display widget with the new state
+        self._w = Columns([(self.reserve_columns, self.states[state]), self._label], focus_column=0)
+        if do_callback:
+            self._emit("postchange", old_state)
+
+    def get_state(self) -> bool | Literal["mixed"]:
+        """Return the state of the checkbox."""
+        return self._state
+
+    state = property(get_state, set_state)
+
+    def keypress(self, size: tuple[int], key: str) -> str | None:
+        """
+        Toggle state on 'activate' command.
+
+        >>> assert CheckBox._command_map[" "] == "activate"
+        >>> assert CheckBox._command_map["enter"] == "activate"
+        >>> size = (10,)
+        >>> cb = CheckBox("press me")
+        >>> cb.state
+        False
+        >>> cb.keypress(size, " ")
+        >>> cb.state
+        True
+        >>> cb.keypress(size, " ")
+        >>> cb.state
+        False
+        """
+        if self._command_map[key] != Command.ACTIVATE:
+            return key
+
+        self.toggle_state()
+        return None
+
+    def toggle_state(self) -> None:
+        """
+        Cycle to the next valid state.
+
+        >>> cb = CheckBox("3-state", has_mixed=True)
+        >>> cb.state
+        False
+        >>> cb.toggle_state()
+        >>> cb.state
+        True
+        >>> cb.toggle_state()
+        >>> cb.state
+        'mixed'
+        >>> cb.toggle_state()
+        >>> cb.state
+        False
+        """
+        if self.state is False:
+            self.set_state(True)
+        elif self.state is True:
+            if self.has_mixed:
+                self.set_state("mixed")
+            else:
+                self.set_state(False)
+        elif self.state == "mixed":
+            self.set_state(False)
+
+    def mouse_event(self, size: tuple[int], event: str, button: int, x: int, y: int, focus: bool) -> bool:
+        """
+        Toggle state on button 1 press.
+
+        >>> size = (20,)
+        >>> cb = CheckBox("clickme")
+        >>> cb.state
+        False
+        >>> cb.mouse_event(size, "mouse press", 1, 2, 0, True)
+        True
+        >>> cb.state
+        True
+        """
+        if button != 1 or not is_mouse_press(event):
+            return False
+        self.toggle_state()
+        return True
+
+
+class RadioButton(CheckBox):
+    states: typing.ClassVar[dict[bool | Literal["mixed"], SelectableIcon]] = {
+        True: SelectableIcon("(X)", 1),
+        False: SelectableIcon("( )", 1),
+        "mixed": SelectableIcon("(#)", 1),
+    }
+    reserve_columns = 4
+
+    @typing.overload
+    def __init__(
+        self,
+        group: MutableSequence[RadioButton],
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool | Literal["first True"] = ...,
+        on_state_change: Callable[[Self, bool, _T], typing.Any] | None = None,
+        user_data: _T = ...,
+    ) -> None: ...
+
+    @typing.overload
+    def __init__(
+        self,
+        group: MutableSequence[RadioButton],
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool | Literal["first True"] = ...,
+        on_state_change: Callable[[Self, bool], typing.Any] | None = None,
+        user_data: None = None,
+    ) -> None: ...
+
+    def __init__(
+        self,
+        group: MutableSequence[RadioButton],
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        state: bool | Literal["first True"] = "first True",
+        on_state_change: Callable[[Self, bool, _T], typing.Any] | Callable[[Self, bool], typing.Any] | None = None,
+        user_data: _T | None = None,
+    ) -> None:
+        """
+        :param group: list for radio buttons in same group
+        :param label: markup for radio button label
+        :param state: False, True, "mixed" or "first True"
+        :param on_state_change: shorthand for connect_signal()
+                                function call for a single 'change' callback
+        :param user_data: user_data for on_state_change
+
+        ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside
+
+        This function will append the new radio button to group.
+        "first True" will set to True if group is empty.
+
+        Signals supported: ``'change'``, ``"postchange"``
+
+        Register signal handler with::
+
+          urwid.connect_signal(radio_button, "change", callback, user_data)
+
+        where callback is callback(radio_button, new_state [,user_data])
+        Unregister signal handlers with::
+
+          urwid.disconnect_signal(radio_button, "change", callback, user_data)
+
+        >>> bgroup = []  # button group
+        >>> b1 = RadioButton(bgroup, "Agree")
+        >>> b2 = RadioButton(bgroup, "Disagree")
+        >>> len(bgroup)
+        2
+        >>> b1
+        
+        >>> b2
+        
+        >>> b2.render((15,), focus=True).text  # ... = b in Python 3
+        [...'( ) Disagree   ']
+        """
+        if state == "first True":
+            state = not group
+
+        self.group = group
+        super().__init__(label, state, False, on_state_change, user_data)  # type: ignore[call-overload]
+        group.append(self)
+
+    def set_state(self, state: bool | Literal["mixed"], do_callback: bool = True) -> None:
+        """
+        Set the RadioButton state.
+
+        state -- True, False or "mixed"
+
+        do_callback -- False to suppress signal from this change
+
+        If state is True all other radio buttons in the same button
+        group will be set to False.
+
+        >>> bgroup = []  # button group
+        >>> b1 = RadioButton(bgroup, "Agree")
+        >>> b2 = RadioButton(bgroup, "Disagree")
+        >>> b3 = RadioButton(bgroup, "Unsure")
+        >>> b1.state, b2.state, b3.state
+        (True, False, False)
+        >>> b2.set_state(True)
+        >>> b1.state, b2.state, b3.state
+        (False, True, False)
+        >>> def relabel_button(radio_button, new_state):
+        ...     radio_button.set_label("Think Harder!")
+        >>> key = connect_signal(b3, "change", relabel_button)
+        >>> b3
+        
+        >>> b3.set_state(True)  # this will trigger the callback
+        >>> b3
+        
+        """
+        if self._state == state:
+            return
+
+        super().set_state(state, do_callback)
+
+        # if we're clearing the state we don't have to worry about
+        # other buttons in the button group
+        if state is not True:
+            return
+
+        # clear the state of each other radio button
+        for cb in self.group:
+            if cb is self:
+                continue
+            if cb.state:
+                cb.state = False
+
+    def toggle_state(self) -> None:
+        """
+        Set state to True.
+
+        >>> bgroup = []  # button group
+        >>> b1 = RadioButton(bgroup, "Agree")
+        >>> b2 = RadioButton(bgroup, "Disagree")
+        >>> b1.state, b2.state
+        (True, False)
+        >>> b2.toggle_state()
+        >>> b1.state, b2.state
+        (False, True)
+        >>> b2.toggle_state()
+        >>> b1.state, b2.state
+        (False, True)
+        """
+        self.set_state(True)
+
+
+class Button(WidgetWrap[Columns]):
+    button_left = Text("<")
+    button_right = Text(">")
+
+    signals: typing.ClassVar[list[str]] = ["click"]
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        on_press: Callable[[Self, _T], typing.Any] | None = None,
+        user_data: _T = ...,
+        *,
+        align: Literal["left", "center", "right"] | Align = ...,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = ...,
+        layout: TextLayout | None = ...,
+    ) -> None: ...
+
+    @typing.overload
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        on_press: Callable[[Self], typing.Any] | None = None,
+        user_data: None = None,
+        *,
+        align: Literal["left", "center", "right"] | Align = ...,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = ...,
+        layout: TextLayout | None = ...,
+    ) -> None: ...
+
+    def __init__(
+        self,
+        label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
+        on_press: Callable[[Self, _T], typing.Any] | Callable[[Self], typing.Any] | None = None,
+        user_data: _T | None = None,
+        *,
+        align: Literal["left", "center", "right"] | Align = Align.LEFT,
+        wrap: Literal["space", "any", "clip", "ellipsis"] | WrapMode = WrapMode.SPACE,
+        layout: TextLayout | None = None,
+    ) -> None:
+        """
+        :param label: markup for button label
+        :param on_press: shorthand for connect_signal()
+                         function call for a single callback
+        :param user_data: user_data for on_press
+        :param align: typically ``'left'``, ``'center'`` or ``'right'``
+        :type align: label alignment mode
+        :param wrap: typically ``'space'``, ``'any'``, ``'clip'`` or ``'ellipsis'``
+        :type wrap: label wrapping mode
+        :param layout: defaults to a shared :class:`StandardTextLayout` instance
+        :type layout: text layout instance
+
+        ..note:: `pack` method expect, that `Columns` backend widget is not modified from outside
+
+        Signals supported: ``'click'``
+
+        Register signal handler with::
+
+          urwid.connect_signal(button, "click", callback, user_data)
+
+        where callback is callback(button [,user_data])
+        Unregister signal handlers with::
+
+          urwid.disconnect_signal(button, "click", callback, user_data)
+
+        >>> from urwid.util import set_temporary_encoding
+        >>> Button("Ok")
+