1# util/preloaded.py
2# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3# <see AUTHORS file>
4#
5# This module is part of SQLAlchemy and is released under
6# the MIT License: https://www.opensource.org/licenses/mit-license.php
7# mypy: allow-untyped-defs, allow-untyped-calls
8
9"""supplies the "preloaded" registry to resolve circular module imports at
10runtime.
11
12"""
13from __future__ import annotations
14
15import sys
16from typing import Any
17from typing import Callable
18from typing import TYPE_CHECKING
19from typing import TypeVar
20
21_FN = TypeVar("_FN", bound=Callable[..., Any])
22
23
24if TYPE_CHECKING:
25 from sqlalchemy import dialects as _dialects
26 from sqlalchemy import orm as _orm
27 from sqlalchemy.engine import cursor as _engine_cursor
28 from sqlalchemy.engine import default as _engine_default
29 from sqlalchemy.engine import reflection as _engine_reflection
30 from sqlalchemy.engine import result as _engine_result
31 from sqlalchemy.engine import url as _engine_url
32 from sqlalchemy.orm import attributes as _orm_attributes
33 from sqlalchemy.orm import base as _orm_base
34 from sqlalchemy.orm import clsregistry as _orm_clsregistry
35 from sqlalchemy.orm import decl_api as _orm_decl_api
36 from sqlalchemy.orm import decl_base as _orm_decl_base
37 from sqlalchemy.orm import dependency as _orm_dependency
38 from sqlalchemy.orm import descriptor_props as _orm_descriptor_props
39 from sqlalchemy.orm import mapperlib as _orm_mapper
40 from sqlalchemy.orm import properties as _orm_properties
41 from sqlalchemy.orm import relationships as _orm_relationships
42 from sqlalchemy.orm import session as _orm_session
43 from sqlalchemy.orm import state as _orm_state
44 from sqlalchemy.orm import strategies as _orm_strategies
45 from sqlalchemy.orm import strategy_options as _orm_strategy_options
46 from sqlalchemy.orm import util as _orm_util
47 from sqlalchemy.sql import default_comparator as _sql_default_comparator
48 from sqlalchemy.sql import dml as _sql_dml
49 from sqlalchemy.sql import elements as _sql_elements
50 from sqlalchemy.sql import functions as _sql_functions
51 from sqlalchemy.sql import naming as _sql_naming
52 from sqlalchemy.sql import schema as _sql_schema
53 from sqlalchemy.sql import selectable as _sql_selectable
54 from sqlalchemy.sql import sqltypes as _sql_sqltypes
55 from sqlalchemy.sql import traversals as _sql_traversals
56 from sqlalchemy.sql import util as _sql_util
57
58 # sigh, appease mypy 0.971 which does not accept imports as instance
59 # variables of a module
60 dialects = _dialects
61 engine_cursor = _engine_cursor
62 engine_default = _engine_default
63 engine_reflection = _engine_reflection
64 engine_result = _engine_result
65 engine_url = _engine_url
66 orm_clsregistry = _orm_clsregistry
67 orm_base = _orm_base
68 orm = _orm
69 orm_attributes = _orm_attributes
70 orm_decl_api = _orm_decl_api
71 orm_decl_base = _orm_decl_base
72 orm_descriptor_props = _orm_descriptor_props
73 orm_dependency = _orm_dependency
74 orm_mapper = _orm_mapper
75 orm_properties = _orm_properties
76 orm_relationships = _orm_relationships
77 orm_session = _orm_session
78 orm_strategies = _orm_strategies
79 orm_strategy_options = _orm_strategy_options
80 orm_state = _orm_state
81 orm_util = _orm_util
82 sql_default_comparator = _sql_default_comparator
83 sql_dml = _sql_dml
84 sql_elements = _sql_elements
85 sql_functions = _sql_functions
86 sql_naming = _sql_naming
87 sql_selectable = _sql_selectable
88 sql_traversals = _sql_traversals
89 sql_schema = _sql_schema
90 sql_sqltypes = _sql_sqltypes
91 sql_util = _sql_util
92
93
94class _ModuleRegistry:
95 """Registry of modules to load in a package init file.
96
97 To avoid potential thread safety issues for imports that are deferred
98 in a function, like https://bugs.python.org/issue38884, these modules
99 are added to the system module cache by importing them after the packages
100 has finished initialization.
101
102 A global instance is provided under the name :attr:`.preloaded`. Use
103 the function :func:`.preload_module` to register modules to load and
104 :meth:`.import_prefix` to load all the modules that start with the
105 given path.
106
107 While the modules are loaded in the global module cache, it's advisable
108 to access them using :attr:`.preloaded` to ensure that it was actually
109 registered. Each registered module is added to the instance ``__dict__``
110 in the form `<package>_<module>`, omitting ``sqlalchemy`` from the package
111 name. Example: ``sqlalchemy.sql.util`` becomes ``preloaded.sql_util``.
112 """
113
114 def __init__(self, prefix="sqlalchemy."):
115 self.module_registry = set()
116 self.prefix = prefix
117
118 def preload_module(self, *deps: str) -> Callable[[_FN], _FN]:
119 """Adds the specified modules to the list to load.
120
121 This method can be used both as a normal function and as a decorator.
122 No change is performed to the decorated object.
123 """
124 self.module_registry.update(deps)
125 return lambda fn: fn
126
127 def import_prefix(self, path: str) -> None:
128 """Resolve all the modules in the registry that start with the
129 specified path.
130 """
131 for module in self.module_registry:
132 if self.prefix:
133 key = module.split(self.prefix)[-1].replace(".", "_")
134 else:
135 key = module
136 if (
137 not path or module.startswith(path)
138 ) and key not in self.__dict__:
139 __import__(module, globals(), locals())
140 self.__dict__[key] = globals()[key] = sys.modules[module]
141
142
143_reg = _ModuleRegistry()
144preload_module = _reg.preload_module
145import_prefix = _reg.import_prefix
146
147# this appears to do absolutely nothing for any version of mypy
148# if TYPE_CHECKING:
149# def __getattr__(key: str) -> ModuleType:
150# ...