activemodel 0.11.0__py3-none-any.whl → 0.13.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- activemodel/base_model.py +113 -88
- activemodel/cli/__init__.py +147 -0
- activemodel/mixins/timestamps.py +4 -1
- activemodel/mixins/typeid.py +1 -1
- activemodel/pytest/__init__.py +1 -1
- activemodel/pytest/factories.py +102 -0
- activemodel/pytest/plugin.py +81 -0
- activemodel/pytest/transaction.py +103 -16
- activemodel/pytest/truncate.py +108 -7
- activemodel/query_wrapper.py +12 -2
- activemodel/session_manager.py +45 -11
- activemodel/types/sqlalchemy_protocol.py +10 -0
- activemodel/types/sqlalchemy_protocol.pyi +132 -0
- activemodel/types/typeid.py +1 -0
- activemodel/utils.py +3 -39
- {activemodel-0.11.0.dist-info → activemodel-0.13.0.dist-info}/METADATA +27 -6
- activemodel-0.13.0.dist-info/RECORD +30 -0
- activemodel-0.13.0.dist-info/entry_points.txt +2 -0
- activemodel-0.11.0.dist-info/RECORD +0 -25
- activemodel-0.11.0.dist-info/entry_points.txt +0 -2
- {activemodel-0.11.0.dist-info → activemodel-0.13.0.dist-info}/WHEEL +0 -0
- {activemodel-0.11.0.dist-info → activemodel-0.13.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,19 +1,107 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import contextvars
|
|
3
|
+
|
|
4
|
+
from sqlmodel import Session
|
|
1
5
|
from activemodel import SessionManager
|
|
6
|
+
from activemodel.session_manager import global_session
|
|
2
7
|
|
|
3
8
|
from ..logger import logger
|
|
4
9
|
|
|
10
|
+
try:
|
|
11
|
+
import factory as factory_exists
|
|
12
|
+
except ImportError:
|
|
13
|
+
factory_exists = None
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import polyfactory as polyfactory_exists
|
|
17
|
+
except ImportError:
|
|
18
|
+
polyfactory_exists = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_test_session = contextvars.ContextVar[Session | None]("test_session", default=None)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def set_factory_session(session):
|
|
25
|
+
if not factory_exists:
|
|
26
|
+
return
|
|
27
|
+
from factory.alchemy import SQLAlchemyModelFactory
|
|
28
|
+
|
|
29
|
+
# Ensure that all factories use the same session
|
|
30
|
+
for factory in SQLAlchemyModelFactory.__subclasses__():
|
|
31
|
+
factory._meta.sqlalchemy_session = factory_session
|
|
32
|
+
factory._meta.sqlalchemy_session_persistence = "commit"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def set_polyfactory_session(session):
|
|
36
|
+
if not polyfactory_exists:
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
from .factories import ActiveModelFactory
|
|
40
|
+
|
|
41
|
+
ActiveModelFactory.__sqlalchemy_session__ = session
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@contextlib.contextmanager
|
|
45
|
+
def test_session():
|
|
46
|
+
"""
|
|
47
|
+
Configures a session-global database session for a test.
|
|
48
|
+
|
|
49
|
+
Use this as a fixture using `db_session`. This method is meant to be used as a context manager.
|
|
50
|
+
|
|
51
|
+
This is useful for tests that need to interact with the database multiple times before calling application code
|
|
52
|
+
that uses the objects. This is intended to be used outside of an integration test. Integration tests generally
|
|
53
|
+
do not use database transactions to clean the database and instead use truncation. The transaction fixture
|
|
54
|
+
configures a session, which is then used here. This method requires that this global test session is already
|
|
55
|
+
configured. If the transaction fixture is not used, then there is no session available for use and this will fail.
|
|
56
|
+
|
|
57
|
+
ActiveModelFactory.save() does this automatically, but if you need to manually create objects
|
|
58
|
+
and persist them to a DB, you can run into issues with the simple `expunge()` call
|
|
59
|
+
used to reassociate an object with a new session. If there are more complex relationships
|
|
60
|
+
this approach will fail and give you detached object errors.
|
|
61
|
+
|
|
62
|
+
>>> from activemodel.pytest import test_session
|
|
63
|
+
>>> def test_the_thing():
|
|
64
|
+
>>> with test_session():
|
|
65
|
+
... obj = MyModel(name="test").save()
|
|
66
|
+
... obj2 = MyModelFactory.save()
|
|
67
|
+
|
|
68
|
+
More information: https://grok.com/share/bGVnYWN5_c21dd39f-84a7-44cf-a05b-9b26c8febb0b
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
if model_factory_session := _test_session.get():
|
|
72
|
+
with global_session(model_factory_session) as session:
|
|
73
|
+
yield session
|
|
74
|
+
else:
|
|
75
|
+
raise ValueError("No test session available")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def database_truncate_session():
|
|
79
|
+
"""
|
|
80
|
+
Provides a database session for testing when using a truncation cleaning strategy.
|
|
81
|
+
|
|
82
|
+
When not using a transaction cleaning strategy, no global test session is set
|
|
83
|
+
"""
|
|
84
|
+
with test_session() as session:
|
|
85
|
+
yield session
|
|
86
|
+
|
|
5
87
|
|
|
6
88
|
def database_reset_transaction():
|
|
7
89
|
"""
|
|
8
90
|
Wrap all database interactions for a given test in a nested transaction and roll it back after the test.
|
|
9
91
|
|
|
92
|
+
This is provided as a function, not a fixture, since you'll need to determine when a integration test is run. Here's
|
|
93
|
+
an example of how to build a fixture from this method:
|
|
94
|
+
|
|
10
95
|
>>> from activemodel.pytest import database_reset_transaction
|
|
11
96
|
>>> database_reset_transaction = pytest.fixture(scope="function", autouse=True)(database_reset_transaction)
|
|
12
97
|
|
|
13
|
-
Transaction-based DB cleaning does *not* work if the DB mutations are happening in a separate process
|
|
14
|
-
|
|
98
|
+
Transaction-based DB cleaning does *not* work if the DB mutations are happening in a separate process because the
|
|
99
|
+
same session is not shared across python processes. For this scenario, use the truncate method.
|
|
15
100
|
|
|
16
|
-
|
|
101
|
+
Note that using `fork` as a multiprocess start method is dangerous. Use spawn. This link has more documentation
|
|
102
|
+
around this topic:
|
|
103
|
+
|
|
104
|
+
https://github.com/iloveitaly/python-starter-template/blob/master/app/configuration/lang.py
|
|
17
105
|
|
|
18
106
|
References:
|
|
19
107
|
|
|
@@ -28,30 +116,29 @@ def database_reset_transaction():
|
|
|
28
116
|
|
|
29
117
|
engine = SessionManager.get_instance().get_engine()
|
|
30
118
|
|
|
31
|
-
logger.
|
|
119
|
+
logger.debug("starting global database transaction")
|
|
32
120
|
|
|
33
121
|
with engine.begin() as connection:
|
|
34
122
|
transaction = connection.begin_nested()
|
|
35
123
|
|
|
36
124
|
if SessionManager.get_instance().session_connection is not None:
|
|
37
|
-
|
|
38
|
-
# TODO should we throw an exception here?
|
|
125
|
+
raise ValueError("global session already set")
|
|
39
126
|
|
|
127
|
+
# NOTE we very intentionally do NOT
|
|
40
128
|
SessionManager.get_instance().session_connection = connection
|
|
41
129
|
|
|
42
130
|
try:
|
|
43
|
-
with SessionManager.get_instance().get_session() as
|
|
44
|
-
|
|
45
|
-
|
|
131
|
+
with SessionManager.get_instance().get_session() as model_factory_session:
|
|
132
|
+
# set global database sessions for model factories to avoid lazy loading issues
|
|
133
|
+
set_factory_session(model_factory_session)
|
|
134
|
+
set_polyfactory_session(model_factory_session)
|
|
46
135
|
|
|
47
|
-
|
|
48
|
-
for factory in SQLAlchemyModelFactory.__subclasses__():
|
|
49
|
-
factory._meta.sqlalchemy_session = factory_session
|
|
50
|
-
factory._meta.sqlalchemy_session_persistence = "commit"
|
|
51
|
-
except ImportError:
|
|
52
|
-
pass
|
|
136
|
+
test_session_token = _test_session.set(model_factory_session)
|
|
53
137
|
|
|
54
|
-
|
|
138
|
+
try:
|
|
139
|
+
yield
|
|
140
|
+
finally:
|
|
141
|
+
_test_session.reset(test_session_token)
|
|
55
142
|
finally:
|
|
56
143
|
logger.debug("rolling back transaction")
|
|
57
144
|
|
activemodel/pytest/truncate.py
CHANGED
|
@@ -1,10 +1,110 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Iterable
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
1
5
|
from sqlmodel import SQLModel
|
|
2
6
|
|
|
3
7
|
from ..logger import logger
|
|
4
8
|
from ..session_manager import get_engine
|
|
9
|
+
from pytest import Config
|
|
10
|
+
import typing as t
|
|
11
|
+
|
|
12
|
+
T = t.TypeVar("T")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _normalize_to_list_of_strings(str_or_list: list[str] | str) -> list[str]:
|
|
16
|
+
if isinstance(str_or_list, list):
|
|
17
|
+
return str_or_list
|
|
18
|
+
|
|
19
|
+
raw_list = str_or_list.split(",")
|
|
20
|
+
return [entry.strip() for entry in raw_list if entry and entry.strip()]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_pytest_option(
|
|
24
|
+
config: Config, key: str, *, cast: t.Callable[[t.Any], T] | None = str
|
|
25
|
+
) -> T | None:
|
|
26
|
+
if not config:
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
val = config.getoption(key)
|
|
31
|
+
except ValueError:
|
|
32
|
+
val = None
|
|
33
|
+
|
|
34
|
+
if val is None:
|
|
35
|
+
val = config.getini(key)
|
|
36
|
+
|
|
37
|
+
if val is not None:
|
|
38
|
+
if cast:
|
|
39
|
+
return cast(val)
|
|
40
|
+
|
|
41
|
+
return val
|
|
42
|
+
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _normalize_preserve_tables(raw: Iterable[str]) -> list[str]:
|
|
47
|
+
"""Normalize user supplied table list: strip, dedupe (order not preserved).
|
|
48
|
+
|
|
49
|
+
Returns a sorted list (case-insensitive sort while preserving original casing
|
|
50
|
+
for readability in logs).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
cleaned = {name.strip() for name in raw if name and name.strip()}
|
|
54
|
+
# deterministic order: casefold sort
|
|
55
|
+
return sorted(cleaned, key=lambda s: s.casefold())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _get_excluded_tables(
|
|
59
|
+
pytest_config: Config | None, preserve_tables: list[str] | None
|
|
60
|
+
) -> list[str]:
|
|
61
|
+
"""Resolve list of tables to exclude (i.e. *preserve* / NOT truncate).
|
|
62
|
+
|
|
63
|
+
Precedence (lowest -> highest):
|
|
64
|
+
1. pytest ini option ``activemodel_preserve_tables`` (if available)
|
|
65
|
+
2. Environment variable ``ACTIVEMODEL_PRESERVE_TABLES`` (comma separated)
|
|
66
|
+
3. Function argument ``preserve_tables``
|
|
67
|
+
|
|
68
|
+
Behavior:
|
|
69
|
+
* If user supplies nothing via any channel, defaults to ["alembic_version"].
|
|
70
|
+
* Case-insensitive matching during truncation; returned list is normalized
|
|
71
|
+
(deduped, sorted) for deterministic logging.
|
|
72
|
+
* Emits a warning only when the ini option is *explicitly* specified but empty after normalization.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
# 1. pytest ini option (registered as type="linelist" -> typically list[str])
|
|
76
|
+
ini_tables = (
|
|
77
|
+
_get_pytest_option(
|
|
78
|
+
pytest_config,
|
|
79
|
+
"activemodel_preserve_tables",
|
|
80
|
+
cast=_normalize_to_list_of_strings,
|
|
81
|
+
)
|
|
82
|
+
or []
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# 2. environment variable
|
|
86
|
+
env_var = os.getenv("ACTIVEMODEL_PRESERVE_TABLES", "")
|
|
87
|
+
env_tables = _normalize_to_list_of_strings(env_var)
|
|
88
|
+
|
|
89
|
+
# 3. function argument
|
|
90
|
+
arg_tables = preserve_tables or []
|
|
91
|
+
|
|
92
|
+
# Consider customization only if any non-empty source provided values OR the function arg explicitly passed
|
|
93
|
+
combined_raw = [*ini_tables, *env_tables, *arg_tables]
|
|
94
|
+
|
|
95
|
+
# if no user customization, force alembic_version
|
|
96
|
+
if not combined_raw:
|
|
97
|
+
return ["alembic_version"]
|
|
98
|
+
|
|
99
|
+
normalized = _normalize_preserve_tables(combined_raw)
|
|
100
|
+
logger.debug(f"excluded tables for truncation: {normalized}")
|
|
101
|
+
|
|
102
|
+
return normalized
|
|
5
103
|
|
|
6
104
|
|
|
7
|
-
def database_reset_truncate(
|
|
105
|
+
def database_reset_truncate(
|
|
106
|
+
preserve_tables: list[str] | None = None, pytest_config: Config | None = None
|
|
107
|
+
):
|
|
8
108
|
"""
|
|
9
109
|
Transaction is most likely the better way to go, but there are some scenarios where the session override
|
|
10
110
|
logic does not work properly and you need to truncate tables back to their original state.
|
|
@@ -28,18 +128,19 @@ def database_reset_truncate():
|
|
|
28
128
|
|
|
29
129
|
logger.info("truncating database")
|
|
30
130
|
|
|
31
|
-
#
|
|
32
|
-
exception_tables =
|
|
131
|
+
# Determine excluded (preserved) tables and build case-insensitive lookup set
|
|
132
|
+
exception_tables = _get_excluded_tables(pytest_config, preserve_tables)
|
|
133
|
+
exception_lookup = {t.lower() for t in exception_tables}
|
|
33
134
|
|
|
34
|
-
assert (
|
|
35
|
-
|
|
36
|
-
)
|
|
135
|
+
assert SQLModel.metadata.sorted_tables, (
|
|
136
|
+
"No model metadata. Ensure model metadata is imported before running truncate_db"
|
|
137
|
+
)
|
|
37
138
|
|
|
38
139
|
with get_engine().connect() as connection:
|
|
39
140
|
for table in reversed(SQLModel.metadata.sorted_tables):
|
|
40
141
|
transaction = connection.begin()
|
|
41
142
|
|
|
42
|
-
if table.name not in
|
|
143
|
+
if table.name.lower() not in exception_lookup:
|
|
43
144
|
logger.debug(f"truncating table={table.name}")
|
|
44
145
|
connection.execute(table.delete())
|
|
45
146
|
|
activemodel/query_wrapper.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import sqlmodel as sm
|
|
2
2
|
from sqlmodel.sql.expression import SelectOfScalar
|
|
3
3
|
|
|
4
|
+
from activemodel.types.sqlalchemy_protocol import SQLAlchemyQueryMethods
|
|
5
|
+
|
|
4
6
|
from .session_manager import get_session
|
|
5
7
|
from .utils import compile_sql
|
|
6
8
|
|
|
7
9
|
|
|
8
|
-
class QueryWrapper[T: sm.SQLModel]:
|
|
10
|
+
class QueryWrapper[T: sm.SQLModel](SQLAlchemyQueryMethods[T]):
|
|
9
11
|
"""
|
|
10
12
|
Make it easy to run queries off of a model
|
|
11
13
|
"""
|
|
@@ -46,13 +48,20 @@ class QueryWrapper[T: sm.SQLModel]:
|
|
|
46
48
|
with get_session() as session:
|
|
47
49
|
return session.scalar(sm.select(sm.func.count()).select_from(self.target))
|
|
48
50
|
|
|
51
|
+
def scalar(self):
|
|
52
|
+
"""
|
|
53
|
+
>>>
|
|
54
|
+
"""
|
|
55
|
+
with get_session() as session:
|
|
56
|
+
return session.scalar(self.target)
|
|
57
|
+
|
|
49
58
|
def exec(self):
|
|
50
59
|
with get_session() as session:
|
|
51
60
|
return session.exec(self.target)
|
|
52
61
|
|
|
53
62
|
def delete(self):
|
|
54
63
|
with get_session() as session:
|
|
55
|
-
session.delete(self.target)
|
|
64
|
+
return session.delete(self.target)
|
|
56
65
|
|
|
57
66
|
def __getattr__(self, name):
|
|
58
67
|
"""
|
|
@@ -87,4 +96,5 @@ class QueryWrapper[T: sm.SQLModel]:
|
|
|
87
96
|
return compile_sql(self.target)
|
|
88
97
|
|
|
89
98
|
def __repr__(self) -> str:
|
|
99
|
+
# TODO we should improve structure of this a bit more, maybe wrap in <> or something?
|
|
90
100
|
return f"{self.__class__.__name__}: Current SQL:\n{self.sql()}"
|
activemodel/session_manager.py
CHANGED
|
@@ -13,6 +13,8 @@ from pydantic import BaseModel
|
|
|
13
13
|
from sqlalchemy import Connection, Engine
|
|
14
14
|
from sqlmodel import Session, create_engine
|
|
15
15
|
|
|
16
|
+
ACTIVEMODEL_LOG_SQL = config("ACTIVEMODEL_LOG_SQL", cast=bool, default=False)
|
|
17
|
+
|
|
16
18
|
|
|
17
19
|
def _serialize_pydantic_model(model: BaseModel | list[BaseModel] | None) -> str | None:
|
|
18
20
|
"""
|
|
@@ -50,18 +52,26 @@ class SessionManager:
|
|
|
50
52
|
"optionally specify a specific session connection to use for all get_session() calls, useful for testing and migrations"
|
|
51
53
|
|
|
52
54
|
@classmethod
|
|
53
|
-
def get_instance(
|
|
55
|
+
def get_instance(
|
|
56
|
+
cls,
|
|
57
|
+
database_url: str | None = None,
|
|
58
|
+
*,
|
|
59
|
+
engine_options: dict[str, t.Any] | None = None,
|
|
60
|
+
) -> "SessionManager":
|
|
54
61
|
if cls._instance is None:
|
|
55
62
|
assert database_url is not None, (
|
|
56
63
|
"Database URL required for first initialization"
|
|
57
64
|
)
|
|
58
|
-
cls._instance = cls(database_url)
|
|
65
|
+
cls._instance = cls(database_url, engine_options=engine_options)
|
|
59
66
|
|
|
60
67
|
return cls._instance
|
|
61
68
|
|
|
62
|
-
def __init__(
|
|
69
|
+
def __init__(
|
|
70
|
+
self, database_url: str, *, engine_options: dict[str, t.Any] | None = None
|
|
71
|
+
):
|
|
63
72
|
self._database_url = database_url
|
|
64
73
|
self._engine = None
|
|
74
|
+
self._engine_options: dict = engine_options or {}
|
|
65
75
|
|
|
66
76
|
self.session_connection = None
|
|
67
77
|
|
|
@@ -72,11 +82,12 @@ class SessionManager:
|
|
|
72
82
|
self._database_url,
|
|
73
83
|
# NOTE very important! This enables pydantic models to be serialized for JSONB columns
|
|
74
84
|
json_serializer=_serialize_pydantic_model,
|
|
75
|
-
|
|
76
|
-
|
|
85
|
+
echo=ACTIVEMODEL_LOG_SQL,
|
|
86
|
+
echo_pool=ACTIVEMODEL_LOG_SQL,
|
|
77
87
|
# https://docs.sqlalchemy.org/en/20/core/pooling.html#disconnect-handling-pessimistic
|
|
78
88
|
pool_pre_ping=True,
|
|
79
89
|
# some implementations include `future=True` but it's not required anymore
|
|
90
|
+
**self._engine_options,
|
|
80
91
|
)
|
|
81
92
|
|
|
82
93
|
return self._engine
|
|
@@ -99,9 +110,10 @@ class SessionManager:
|
|
|
99
110
|
return Session(self.get_engine())
|
|
100
111
|
|
|
101
112
|
|
|
102
|
-
|
|
113
|
+
# TODO would be great one day to type engine_options as the SQLAlchemy EngineOptions
|
|
114
|
+
def init(database_url: str, *, engine_options: dict[str, t.Any] | None = None):
|
|
103
115
|
"configure activemodel to connect to a specific database"
|
|
104
|
-
return SessionManager.get_instance(database_url)
|
|
116
|
+
return SessionManager.get_instance(database_url, engine_options=engine_options)
|
|
105
117
|
|
|
106
118
|
|
|
107
119
|
def get_engine():
|
|
@@ -128,18 +140,40 @@ a place to persist a session to use globally across the application.
|
|
|
128
140
|
|
|
129
141
|
|
|
130
142
|
@contextlib.contextmanager
|
|
131
|
-
def global_session():
|
|
143
|
+
def global_session(session: Session | None = None):
|
|
132
144
|
"""
|
|
133
|
-
Generate a session
|
|
145
|
+
Generate a session and share it across all activemodel calls.
|
|
134
146
|
|
|
135
147
|
Alternatively, you can pass a session to use globally into the context manager, which is helpful for migrations
|
|
136
148
|
and testing.
|
|
149
|
+
|
|
150
|
+
This may only be called a single time per callstack. There is one exception: if you call this multiple times
|
|
151
|
+
and pass in the same session reference, it will result in a noop.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
session: Use an existing session instead of creating a new one
|
|
137
155
|
"""
|
|
138
156
|
|
|
157
|
+
if session is not None and _session_context.get() is session:
|
|
158
|
+
yield session
|
|
159
|
+
return
|
|
160
|
+
|
|
139
161
|
if _session_context.get() is not None:
|
|
140
|
-
raise RuntimeError("global session already set")
|
|
162
|
+
raise RuntimeError("ActiveModel: global session already set")
|
|
141
163
|
|
|
142
|
-
|
|
164
|
+
@contextlib.contextmanager
|
|
165
|
+
def manage_existing_session():
|
|
166
|
+
"if an existing session already exists, use it without triggering another __enter__"
|
|
167
|
+
yield session
|
|
168
|
+
|
|
169
|
+
# Use provided session or create a new one
|
|
170
|
+
session_context = (
|
|
171
|
+
manage_existing_session()
|
|
172
|
+
if session is not None
|
|
173
|
+
else SessionManager.get_instance().get_session()
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
with session_context as s:
|
|
143
177
|
token = _session_context.set(s)
|
|
144
178
|
|
|
145
179
|
try:
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# IMPORTANT: This file is auto-generated. Do not edit directly.
|
|
2
|
+
|
|
3
|
+
from typing import Protocol, TypeVar, Any, Generic
|
|
4
|
+
import sqlmodel as sm
|
|
5
|
+
from sqlalchemy.sql.base import _NoArg
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SQLAlchemyQueryMethods[T: sm.SQLModel](Protocol):
|
|
10
|
+
pass
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# IMPORTANT: This file is auto-generated. Do not edit directly.
|
|
2
|
+
|
|
3
|
+
from typing import Protocol, TypeVar, Any, Generic
|
|
4
|
+
import sqlmodel as sm
|
|
5
|
+
from sqlalchemy.sql.base import _NoArg
|
|
6
|
+
|
|
7
|
+
from ..query_wrapper import QueryWrapper
|
|
8
|
+
|
|
9
|
+
class SQLAlchemyQueryMethods[T: sm.SQLModel](Protocol):
|
|
10
|
+
"""Protocol defining SQLAlchemy query methods forwarded by QueryWrapper.__getattr__"""
|
|
11
|
+
|
|
12
|
+
def add_columns(self, *entities: Any) -> "QueryWrapper[T]": ...
|
|
13
|
+
def add_cte(self, *ctes: Any, nest_here: Any = False) -> "QueryWrapper[T]": ...
|
|
14
|
+
def alias(self, name: Any = None, flat: Any = False) -> "QueryWrapper[T]": ...
|
|
15
|
+
def argument_for(self, argument_name: Any, default: Any) -> "QueryWrapper[T]": ...
|
|
16
|
+
def as_scalar(
|
|
17
|
+
self,
|
|
18
|
+
) -> "QueryWrapper[T]": ...
|
|
19
|
+
def column(self, column: Any) -> "QueryWrapper[T]": ...
|
|
20
|
+
def compare(self, other: Any, **kw: Any) -> "QueryWrapper[T]": ...
|
|
21
|
+
def compile(
|
|
22
|
+
self, bind: Any = None, dialect: Any = None, **kw: Any
|
|
23
|
+
) -> "QueryWrapper[T]": ...
|
|
24
|
+
def correlate(self, *fromclauses: Any) -> "QueryWrapper[T]": ...
|
|
25
|
+
def correlate_except(self, *fromclauses: Any) -> "QueryWrapper[T]": ...
|
|
26
|
+
def corresponding_column(
|
|
27
|
+
self, column: Any, require_embedded: Any = False
|
|
28
|
+
) -> "QueryWrapper[T]": ...
|
|
29
|
+
def cte(
|
|
30
|
+
self, name: Any = None, recursive: Any = False, nesting: Any = False
|
|
31
|
+
) -> "QueryWrapper[T]": ...
|
|
32
|
+
def distinct(self, *expr: Any) -> "QueryWrapper[T]": ...
|
|
33
|
+
def except_(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
34
|
+
def except_all(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
35
|
+
def execution_options(self, **kw: Any) -> "QueryWrapper[T]": ...
|
|
36
|
+
def exists(
|
|
37
|
+
self,
|
|
38
|
+
) -> "QueryWrapper[T]": ...
|
|
39
|
+
def fetch(
|
|
40
|
+
self,
|
|
41
|
+
count: Any,
|
|
42
|
+
with_ties: Any = False,
|
|
43
|
+
percent: Any = False,
|
|
44
|
+
**dialect_kw: Any,
|
|
45
|
+
) -> "QueryWrapper[T]": ...
|
|
46
|
+
def filter(self, *criteria: Any) -> "QueryWrapper[T]": ...
|
|
47
|
+
def filter_by(self, **kwargs: Any) -> "QueryWrapper[T]": ...
|
|
48
|
+
def from_statement(self, statement: Any) -> "QueryWrapper[T]": ...
|
|
49
|
+
def get_children(self, **kw: Any) -> "QueryWrapper[T]": ...
|
|
50
|
+
def get_execution_options(
|
|
51
|
+
self,
|
|
52
|
+
) -> "QueryWrapper[T]": ...
|
|
53
|
+
def get_final_froms(
|
|
54
|
+
self,
|
|
55
|
+
) -> "QueryWrapper[T]": ...
|
|
56
|
+
def get_label_style(
|
|
57
|
+
self,
|
|
58
|
+
) -> "QueryWrapper[T]": ...
|
|
59
|
+
def group_by(
|
|
60
|
+
self, _GenerativeSelect__first: Any = _NoArg.NO_ARG, *clauses: Any
|
|
61
|
+
) -> "QueryWrapper[T]": ...
|
|
62
|
+
def having(self, *having: Any) -> "QueryWrapper[T]": ...
|
|
63
|
+
def intersect(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
64
|
+
def intersect_all(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
65
|
+
def is_derived_from(self, fromclause: Any) -> "QueryWrapper[T]": ...
|
|
66
|
+
def join(
|
|
67
|
+
self, target: Any, onclause: Any = None, isouter: Any = False, full: Any = False
|
|
68
|
+
) -> "QueryWrapper[T]": ...
|
|
69
|
+
def join_from(
|
|
70
|
+
self,
|
|
71
|
+
from_: Any,
|
|
72
|
+
target: Any,
|
|
73
|
+
onclause: Any = None,
|
|
74
|
+
isouter: Any = False,
|
|
75
|
+
full: Any = False,
|
|
76
|
+
) -> "QueryWrapper[T]": ...
|
|
77
|
+
def label(self, name: Any) -> "QueryWrapper[T]": ...
|
|
78
|
+
def lateral(self, name: Any = None) -> "QueryWrapper[T]": ...
|
|
79
|
+
def limit(self, limit: Any) -> "QueryWrapper[T]": ...
|
|
80
|
+
def memoized_instancemethod(
|
|
81
|
+
self,
|
|
82
|
+
) -> "QueryWrapper[T]": ...
|
|
83
|
+
def offset(self, offset: Any) -> "QueryWrapper[T]": ...
|
|
84
|
+
def options(self, *options: Any) -> "QueryWrapper[T]": ...
|
|
85
|
+
def order_by(
|
|
86
|
+
self, _GenerativeSelect__first: Any = _NoArg.NO_ARG, *clauses: Any
|
|
87
|
+
) -> QueryWrapper[T]: ...
|
|
88
|
+
def outerjoin(
|
|
89
|
+
self, target: Any, onclause: Any = None, full: Any = False
|
|
90
|
+
) -> "QueryWrapper[T]": ...
|
|
91
|
+
def outerjoin_from(
|
|
92
|
+
self, from_: Any, target: Any, onclause: Any = None, full: Any = False
|
|
93
|
+
) -> "QueryWrapper[T]": ...
|
|
94
|
+
def params(
|
|
95
|
+
self, _ClauseElement__optionaldict: Any = None, **kwargs: Any
|
|
96
|
+
) -> "QueryWrapper[T]": ...
|
|
97
|
+
def prefix_with(self, *prefixes: Any, dialect: Any = "*") -> "QueryWrapper[T]": ...
|
|
98
|
+
def reduce_columns(self, only_synonyms: Any = True) -> "QueryWrapper[T]": ...
|
|
99
|
+
def replace_selectable(self, old: Any, alias: Any) -> "QueryWrapper[T]": ...
|
|
100
|
+
def scalar_subquery(
|
|
101
|
+
self,
|
|
102
|
+
) -> "QueryWrapper[T]": ...
|
|
103
|
+
def select(self, *arg: Any, **kw: Any) -> "QueryWrapper[T]": ...
|
|
104
|
+
def select_from(self, *froms: Any) -> "QueryWrapper[T]": ...
|
|
105
|
+
def self_group(self, against: Any = None) -> "QueryWrapper[T]": ...
|
|
106
|
+
def set_label_style(self, style: Any) -> "QueryWrapper[T]": ...
|
|
107
|
+
def slice(self, start: Any, stop: Any) -> "QueryWrapper[T]": ...
|
|
108
|
+
def subquery(self, name: Any = None) -> "QueryWrapper[T]": ...
|
|
109
|
+
def suffix_with(self, *suffixes: Any, dialect: Any = "*") -> "QueryWrapper[T]": ...
|
|
110
|
+
def union(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
111
|
+
def union_all(self, *other: Any) -> "QueryWrapper[T]": ...
|
|
112
|
+
def unique_params(
|
|
113
|
+
self, _ClauseElement__optionaldict: Any = None, **kwargs: Any
|
|
114
|
+
) -> "QueryWrapper[T]": ...
|
|
115
|
+
def where(self, *whereclause: Any) -> "QueryWrapper[T]": ...
|
|
116
|
+
def with_for_update(
|
|
117
|
+
self,
|
|
118
|
+
nowait: Any = False,
|
|
119
|
+
read: Any = False,
|
|
120
|
+
of: Any = None,
|
|
121
|
+
skip_locked: Any = False,
|
|
122
|
+
key_share: Any = False,
|
|
123
|
+
) -> "QueryWrapper[T]": ...
|
|
124
|
+
def with_hint(
|
|
125
|
+
self, selectable: Any, text: Any, dialect_name: Any = "*"
|
|
126
|
+
) -> "QueryWrapper[T]": ...
|
|
127
|
+
def with_only_columns(
|
|
128
|
+
self, *entities: Any, maintain_column_froms: Any = False, **_Select__kw: Any
|
|
129
|
+
) -> "QueryWrapper[T]": ...
|
|
130
|
+
def with_statement_hint(
|
|
131
|
+
self, text: Any, dialect_name: Any = "*"
|
|
132
|
+
) -> "QueryWrapper[T]": ...
|
activemodel/types/typeid.py
CHANGED
|
@@ -76,6 +76,7 @@ class TypeIDType(types.TypeDecorator):
|
|
|
76
76
|
if isinstance(value, str):
|
|
77
77
|
# no prefix, raw UUID, let's coerce it into a UUID which SQLAlchemy can handle
|
|
78
78
|
# ex: '01942886-7afc-7129-8f57-db09137ed002'
|
|
79
|
+
# if an invalid uuid is passed, `ValueError('badly formed hexadecimal UUID string')` will be raised
|
|
79
80
|
return UUID(value)
|
|
80
81
|
|
|
81
82
|
if isinstance(value, TypeID):
|
activemodel/utils.py
CHANGED
|
@@ -1,18 +1,12 @@
|
|
|
1
|
-
import inspect
|
|
2
|
-
import pkgutil
|
|
3
|
-
import sys
|
|
4
|
-
from types import ModuleType
|
|
5
|
-
|
|
6
1
|
from sqlalchemy import text
|
|
7
|
-
from sqlmodel import SQLModel
|
|
8
2
|
from sqlmodel.sql.expression import SelectOfScalar
|
|
9
3
|
|
|
10
|
-
from .logger import logger
|
|
11
4
|
from .session_manager import get_engine, get_session
|
|
12
5
|
|
|
13
6
|
|
|
14
|
-
def compile_sql(target: SelectOfScalar):
|
|
15
|
-
"convert a query into SQL, helpful for debugging"
|
|
7
|
+
def compile_sql(target: SelectOfScalar) -> str:
|
|
8
|
+
"convert a query into SQL, helpful for debugging sqlalchemy/sqlmodel queries"
|
|
9
|
+
|
|
16
10
|
dialect = get_engine().dialect
|
|
17
11
|
# TODO I wonder if we could store the dialect to avoid getting an engine reference
|
|
18
12
|
compiled = target.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
|
|
@@ -25,36 +19,6 @@ def raw_sql_exec(raw_query: str):
|
|
|
25
19
|
session.execute(text(raw_query))
|
|
26
20
|
|
|
27
21
|
|
|
28
|
-
def find_all_sqlmodels(module: ModuleType):
|
|
29
|
-
"""Import all model classes from module and submodules into current namespace."""
|
|
30
|
-
|
|
31
|
-
logger.debug(f"Starting model import from module: {module.__name__}")
|
|
32
|
-
model_classes = {}
|
|
33
|
-
|
|
34
|
-
# Walk through all submodules
|
|
35
|
-
for loader, module_name, is_pkg in pkgutil.walk_packages(module.__path__):
|
|
36
|
-
full_name = f"{module.__name__}.{module_name}"
|
|
37
|
-
logger.debug(f"Importing submodule: {full_name}")
|
|
38
|
-
|
|
39
|
-
# Check if module is already imported
|
|
40
|
-
if full_name in sys.modules:
|
|
41
|
-
submodule = sys.modules[full_name]
|
|
42
|
-
else:
|
|
43
|
-
logger.warning(
|
|
44
|
-
f"Module not found in sys.modules, not importing: {full_name}"
|
|
45
|
-
)
|
|
46
|
-
continue
|
|
47
|
-
|
|
48
|
-
# Get all classes from module
|
|
49
|
-
for name, obj in inspect.getmembers(submodule):
|
|
50
|
-
if inspect.isclass(obj) and issubclass(obj, SQLModel) and obj != SQLModel:
|
|
51
|
-
logger.debug(f"Found model class: {name}")
|
|
52
|
-
model_classes[name] = obj
|
|
53
|
-
|
|
54
|
-
logger.debug(f"Completed model import. Found {len(model_classes)} models")
|
|
55
|
-
return model_classes
|
|
56
|
-
|
|
57
|
-
|
|
58
22
|
def hash_function_code(func):
|
|
59
23
|
"get sha of a function to easily assert that it hasn't changed"
|
|
60
24
|
|