diracx-db 0.0.1a16__py3-none-any.whl → 0.0.1a18__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diracx/db/os/utils.py +60 -11
- diracx/db/sql/__init__.py +3 -1
- diracx/db/sql/auth/db.py +10 -19
- diracx/db/sql/auth/schema.py +5 -7
- diracx/db/sql/dummy/db.py +2 -3
- diracx/db/sql/{jobs → job}/db.py +12 -452
- diracx/db/sql/{jobs → job}/schema.py +2 -118
- diracx/db/sql/job_logging/__init__.py +0 -0
- diracx/db/sql/job_logging/db.py +161 -0
- diracx/db/sql/job_logging/schema.py +25 -0
- diracx/db/sql/sandbox_metadata/db.py +12 -10
- diracx/db/sql/task_queue/__init__.py +0 -0
- diracx/db/sql/task_queue/db.py +261 -0
- diracx/db/sql/task_queue/schema.py +109 -0
- diracx/db/sql/utils/__init__.py +418 -0
- diracx/db/sql/{jobs/status_utility.py → utils/job_status.py} +12 -19
- {diracx_db-0.0.1a16.dist-info → diracx_db-0.0.1a18.dist-info}/METADATA +5 -5
- diracx_db-0.0.1a18.dist-info/RECORD +33 -0
- {diracx_db-0.0.1a16.dist-info → diracx_db-0.0.1a18.dist-info}/WHEEL +1 -1
- diracx/db/sql/utils.py +0 -234
- diracx_db-0.0.1a16.dist-info/RECORD +0 -27
- /diracx/db/sql/{jobs → job}/__init__.py +0 -0
- {diracx_db-0.0.1a16.dist-info → diracx_db-0.0.1a18.dist-info}/entry_points.txt +0 -0
- {diracx_db-0.0.1a16.dist-info → diracx_db-0.0.1a18.dist-info}/top_level.txt +0 -0
diracx/db/sql/utils.py
DELETED
@@ -1,234 +0,0 @@
|
|
1
|
-
from __future__ import annotations
|
2
|
-
|
3
|
-
__all__ = ("utcnow", "Column", "NullColumn", "DateNowColumn", "BaseSQLDB")
|
4
|
-
|
5
|
-
import contextlib
|
6
|
-
import logging
|
7
|
-
import os
|
8
|
-
from abc import ABCMeta
|
9
|
-
from contextvars import ContextVar
|
10
|
-
from datetime import datetime, timedelta, timezone
|
11
|
-
from functools import partial
|
12
|
-
from typing import TYPE_CHECKING, AsyncIterator, Self, cast
|
13
|
-
|
14
|
-
from pydantic import parse_obj_as
|
15
|
-
from sqlalchemy import Column as RawColumn
|
16
|
-
from sqlalchemy import DateTime, Enum, MetaData, select
|
17
|
-
from sqlalchemy.exc import OperationalError
|
18
|
-
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, create_async_engine
|
19
|
-
from sqlalchemy.ext.compiler import compiles
|
20
|
-
from sqlalchemy.sql import expression
|
21
|
-
|
22
|
-
from diracx.core.exceptions import InvalidQueryError
|
23
|
-
from diracx.core.extensions import select_from_extension
|
24
|
-
from diracx.core.settings import SqlalchemyDsn
|
25
|
-
from diracx.db.exceptions import DBUnavailable
|
26
|
-
|
27
|
-
if TYPE_CHECKING:
|
28
|
-
from sqlalchemy.types import TypeEngine
|
29
|
-
|
30
|
-
logger = logging.getLogger(__name__)
|
31
|
-
|
32
|
-
|
33
|
-
class utcnow(expression.FunctionElement):
|
34
|
-
type: TypeEngine = DateTime()
|
35
|
-
inherit_cache: bool = True
|
36
|
-
|
37
|
-
|
38
|
-
@compiles(utcnow, "postgresql")
|
39
|
-
def pg_utcnow(element, compiler, **kw) -> str:
|
40
|
-
return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
|
41
|
-
|
42
|
-
|
43
|
-
@compiles(utcnow, "mssql")
|
44
|
-
def ms_utcnow(element, compiler, **kw) -> str:
|
45
|
-
return "GETUTCDATE()"
|
46
|
-
|
47
|
-
|
48
|
-
@compiles(utcnow, "mysql")
|
49
|
-
def mysql_utcnow(element, compiler, **kw) -> str:
|
50
|
-
return "(UTC_TIMESTAMP)"
|
51
|
-
|
52
|
-
|
53
|
-
@compiles(utcnow, "sqlite")
|
54
|
-
def sqlite_utcnow(element, compiler, **kw) -> str:
|
55
|
-
return "DATETIME('now')"
|
56
|
-
|
57
|
-
|
58
|
-
def substract_date(**kwargs: float) -> datetime:
|
59
|
-
return datetime.now(tz=timezone.utc) - timedelta(**kwargs)
|
60
|
-
|
61
|
-
|
62
|
-
Column: partial[RawColumn] = partial(RawColumn, nullable=False)
|
63
|
-
NullColumn: partial[RawColumn] = partial(RawColumn, nullable=True)
|
64
|
-
DateNowColumn = partial(Column, DateTime(timezone=True), server_default=utcnow())
|
65
|
-
|
66
|
-
|
67
|
-
def EnumColumn(enum_type, **kwargs):
|
68
|
-
return Column(Enum(enum_type, native_enum=False, length=16), **kwargs)
|
69
|
-
|
70
|
-
|
71
|
-
class SQLDBError(Exception):
|
72
|
-
pass
|
73
|
-
|
74
|
-
|
75
|
-
class SQLDBUnavailable(DBUnavailable, SQLDBError):
|
76
|
-
"""Used whenever we encounter a problem with the B connection"""
|
77
|
-
|
78
|
-
|
79
|
-
class BaseSQLDB(metaclass=ABCMeta):
|
80
|
-
"""This should be the base class of all the DiracX DBs"""
|
81
|
-
|
82
|
-
# engine: AsyncEngine
|
83
|
-
# TODO: Make metadata an abstract property
|
84
|
-
metadata: MetaData
|
85
|
-
|
86
|
-
def __init__(self, db_url: str) -> None:
|
87
|
-
# We use a ContextVar to make sure that self._conn
|
88
|
-
# is specific to each context, and avoid parallel
|
89
|
-
# route executions to overlap
|
90
|
-
self._conn: ContextVar[AsyncConnection | None] = ContextVar(
|
91
|
-
"_conn", default=None
|
92
|
-
)
|
93
|
-
self._db_url = db_url
|
94
|
-
self._engine: AsyncEngine | None = None
|
95
|
-
|
96
|
-
@classmethod
|
97
|
-
def available_implementations(cls, db_name: str) -> list[type[BaseSQLDB]]:
|
98
|
-
"""Return the available implementations of the DB in reverse priority order."""
|
99
|
-
db_classes: list[type[BaseSQLDB]] = [
|
100
|
-
entry_point.load()
|
101
|
-
for entry_point in select_from_extension(
|
102
|
-
group="diracx.db.sql", name=db_name
|
103
|
-
)
|
104
|
-
]
|
105
|
-
if not db_classes:
|
106
|
-
raise NotImplementedError(f"Could not find any matches for {db_name=}")
|
107
|
-
return db_classes
|
108
|
-
|
109
|
-
@classmethod
|
110
|
-
def available_urls(cls) -> dict[str, str]:
|
111
|
-
"""Return a dict of available database urls.
|
112
|
-
|
113
|
-
The list of available URLs is determined by environment variables
|
114
|
-
prefixed with ``DIRACX_DB_URL_{DB_NAME}``.
|
115
|
-
"""
|
116
|
-
db_urls: dict[str, str] = {}
|
117
|
-
for entry_point in select_from_extension(group="diracx.db.sql"):
|
118
|
-
db_name = entry_point.name
|
119
|
-
var_name = f"DIRACX_DB_URL_{entry_point.name.upper()}"
|
120
|
-
if var_name in os.environ:
|
121
|
-
try:
|
122
|
-
db_url = os.environ[var_name]
|
123
|
-
if db_url == "sqlite+aiosqlite:///:memory:":
|
124
|
-
db_urls[db_name] = db_url
|
125
|
-
else:
|
126
|
-
db_urls[db_name] = parse_obj_as(SqlalchemyDsn, db_url)
|
127
|
-
except Exception:
|
128
|
-
logger.error("Error loading URL for %s", db_name)
|
129
|
-
raise
|
130
|
-
return db_urls
|
131
|
-
|
132
|
-
@classmethod
|
133
|
-
def transaction(cls) -> Self:
|
134
|
-
raise NotImplementedError("This should never be called")
|
135
|
-
|
136
|
-
@property
|
137
|
-
def engine(self) -> AsyncEngine:
|
138
|
-
"""The engine to use for database operations.
|
139
|
-
|
140
|
-
It is normally not necessary to use the engine directly,
|
141
|
-
unless you are doing something special, like writing a
|
142
|
-
test fixture that gives you a db.
|
143
|
-
|
144
|
-
|
145
|
-
Requires that the engine_context has been entered.
|
146
|
-
|
147
|
-
"""
|
148
|
-
assert self._engine is not None, "engine_context must be entered"
|
149
|
-
return self._engine
|
150
|
-
|
151
|
-
@contextlib.asynccontextmanager
|
152
|
-
async def engine_context(self) -> AsyncIterator[None]:
|
153
|
-
"""Context manage to manage the engine lifecycle.
|
154
|
-
This is called once at the application startup
|
155
|
-
(see ``lifetime_functions``)
|
156
|
-
"""
|
157
|
-
assert self._engine is None, "engine_context cannot be nested"
|
158
|
-
|
159
|
-
# Set the pool_recycle to 30mn
|
160
|
-
# That should prevent the problem of MySQL expiring connection
|
161
|
-
# after 60mn by default
|
162
|
-
engine = create_async_engine(self._db_url, pool_recycle=60 * 30)
|
163
|
-
self._engine = engine
|
164
|
-
|
165
|
-
yield
|
166
|
-
|
167
|
-
self._engine = None
|
168
|
-
await engine.dispose()
|
169
|
-
|
170
|
-
@property
|
171
|
-
def conn(self) -> AsyncConnection:
|
172
|
-
if self._conn.get() is None:
|
173
|
-
raise RuntimeError(f"{self.__class__} was used before entering")
|
174
|
-
return cast(AsyncConnection, self._conn.get())
|
175
|
-
|
176
|
-
async def __aenter__(self) -> Self:
|
177
|
-
"""
|
178
|
-
Create a connection.
|
179
|
-
This is called by the Dependency mechanism (see ``db_transaction``),
|
180
|
-
It will create a new connection/transaction for each route call.
|
181
|
-
"""
|
182
|
-
assert self._conn.get() is None, "BaseSQLDB context cannot be nested"
|
183
|
-
try:
|
184
|
-
self._conn.set(await self.engine.connect().__aenter__())
|
185
|
-
except Exception as e:
|
186
|
-
raise SQLDBUnavailable("Cannot connect to DB") from e
|
187
|
-
|
188
|
-
return self
|
189
|
-
|
190
|
-
async def __aexit__(self, exc_type, exc, tb):
|
191
|
-
"""
|
192
|
-
This is called when exciting a route.
|
193
|
-
If there was no exception, the changes in the DB are committed.
|
194
|
-
Otherwise, they are rollbacked.
|
195
|
-
"""
|
196
|
-
if exc_type is None:
|
197
|
-
await self._conn.get().commit()
|
198
|
-
await self._conn.get().__aexit__(exc_type, exc, tb)
|
199
|
-
self._conn.set(None)
|
200
|
-
|
201
|
-
async def ping(self):
|
202
|
-
"""
|
203
|
-
Check whether the connection to the DB is still working.
|
204
|
-
We could enable the ``pre_ping`` in the engine, but this would
|
205
|
-
be ran at every query.
|
206
|
-
"""
|
207
|
-
try:
|
208
|
-
await self.conn.scalar(select(1))
|
209
|
-
except OperationalError as e:
|
210
|
-
raise SQLDBUnavailable("Cannot ping the DB") from e
|
211
|
-
|
212
|
-
|
213
|
-
def apply_search_filters(table, stmt, search):
|
214
|
-
# Apply any filters
|
215
|
-
for query in search:
|
216
|
-
column = table.columns[query["parameter"]]
|
217
|
-
if query["operator"] == "eq":
|
218
|
-
expr = column == query["value"]
|
219
|
-
elif query["operator"] == "neq":
|
220
|
-
expr = column != query["value"]
|
221
|
-
elif query["operator"] == "gt":
|
222
|
-
expr = column > query["value"]
|
223
|
-
elif query["operator"] == "lt":
|
224
|
-
expr = column < query["value"]
|
225
|
-
elif query["operator"] == "in":
|
226
|
-
expr = column.in_(query["values"])
|
227
|
-
elif query["operator"] in "like":
|
228
|
-
expr = column.like(query["value"])
|
229
|
-
elif query["operator"] in "ilike":
|
230
|
-
expr = column.ilike(query["value"])
|
231
|
-
else:
|
232
|
-
raise InvalidQueryError(f"Unknown filter {query=}")
|
233
|
-
stmt = stmt.where(expr)
|
234
|
-
return stmt
|
@@ -1,27 +0,0 @@
|
|
1
|
-
diracx/db/__init__.py,sha256=2oeUeVwZq53bo_ZOflEYZsBn7tcR5Tzb2AIu0TAWELM,109
|
2
|
-
diracx/db/__main__.py,sha256=3yaUP1ig-yaPSQM4wy6CtSXXHivQg-hIz2FeBt7joBc,1714
|
3
|
-
diracx/db/exceptions.py,sha256=-LSkEwsvjwU7vXqx-xeLvLKInTRAhjwB7K_AKfQcIH8,41
|
4
|
-
diracx/db/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
5
|
-
diracx/db/os/__init__.py,sha256=IZr6z6SefrRvuC8sTC4RmB3_wwOyEt1GzpDuwSMH8O4,112
|
6
|
-
diracx/db/os/job_parameters.py,sha256=Knca19uT2G-5FI7MOFlaOAXeHn4ecPVLIH30TiwhaTw,858
|
7
|
-
diracx/db/os/utils.py,sha256=mau0_2uRi-I3geefmKQRWFKo4JcIkIUADvnwBiQX700,9129
|
8
|
-
diracx/db/sql/__init__.py,sha256=R6tk5lo1EHbt8joGDesesYHcc1swIq9T4AaSixhh7lA,252
|
9
|
-
diracx/db/sql/utils.py,sha256=BuXjIuXN-_v8YkCoMoMhw2tHVUqG6lTBx-e4VEYWE8o,7857
|
10
|
-
diracx/db/sql/auth/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
11
|
-
diracx/db/sql/auth/db.py,sha256=mKjy5B8orw0yu6nOwxyzbBqyeE-J9iYq6fKjuELmr9g,10273
|
12
|
-
diracx/db/sql/auth/schema.py,sha256=JCkSa2IRzqMHTpaSc9aB9h33XsFyEM_Ohsenex6xagY,2835
|
13
|
-
diracx/db/sql/dummy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
14
|
-
diracx/db/sql/dummy/db.py,sha256=5PIPv6aKY7CGIwmvnGKowjVr9ZQWpbjFSd2PIX7YOUw,1627
|
15
|
-
diracx/db/sql/dummy/schema.py,sha256=uEkGDNVZbmJecytkHY1CO-M1MiKxe5w1_h0joJMPC9E,680
|
16
|
-
diracx/db/sql/jobs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
17
|
-
diracx/db/sql/jobs/db.py,sha256=CyQIPX2g5ancBIBEMLijAyTi5HZxTgeVH0qQZ3p3KcU,30722
|
18
|
-
diracx/db/sql/jobs/schema.py,sha256=YkxIdjTkvLlEZ9IQt86nj80eMvOPbcrfk9aisjmNpqY,9275
|
19
|
-
diracx/db/sql/jobs/status_utility.py,sha256=YZzQfU96A062NC4MkB5-0y96TCPq8Y8dfNBEETzPtrw,10528
|
20
|
-
diracx/db/sql/sandbox_metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
21
|
-
diracx/db/sql/sandbox_metadata/db.py,sha256=0EDFMfOW_O3pEPTShqBCME9z4j-JKpyYM6-BBccr27E,6303
|
22
|
-
diracx/db/sql/sandbox_metadata/schema.py,sha256=rngYYkJxBhjETBHGLD1CTipDGe44mRYR0wdaFoAJwp0,1400
|
23
|
-
diracx_db-0.0.1a16.dist-info/METADATA,sha256=-weqkdxDh05swLO8E-bkWpbhm_Zno2qUnRyKy1pzA7c,681
|
24
|
-
diracx_db-0.0.1a16.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
25
|
-
diracx_db-0.0.1a16.dist-info/entry_points.txt,sha256=xEFGu_zgmPgQPlUeFtdahQfQIboJ1ugFOK8eMio9gtw,271
|
26
|
-
diracx_db-0.0.1a16.dist-info/top_level.txt,sha256=vJx10tdRlBX3rF2Psgk5jlwVGZNcL3m_7iQWwgPXt-U,7
|
27
|
-
diracx_db-0.0.1a16.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|