SQL Utilities
Utilities for SQL database operations.
Base Classes
base
Attributes
logger = logging.getLogger(__name__)
module-attribute
Classes
SQLDBError
SQLDBUnavailableError
Bases: DBUnavailableError, SQLDBError
Used whenever we encounter a problem with the B connection.
BaseSQLDB
This should be the base class of all the SQL DiracX DBs.
The details covered here should be handled automatically by the service and task machinery of DiracX and this documentation exists for informational purposes.
The available databases are discovered by calling BaseSQLDB.available_urls.
This method returns a mapping of database names to connection URLs. The
available databases are determined by the diracx.dbs.sql entrypoint in the
pyproject.toml file and the connection URLs are taken from the environment
variables of the form DIRACX_DB_URL_<db-name>.
If extensions to DiracX are being used, there can be multiple implementations
of the same database. To list the available implementations use
BaseSQLDB.available_implementations(db_name). The first entry in this list
will be the preferred implementation and it can be initialized by calling
it's __init__ function with a URL previously obtained from
BaseSQLDB.available_urls.
To control the lifetime of the SQLAlchemy engine used for connecting to the
database, which includes the connection pool, the BaseSQLDB.engine_context
asynchronous context manager should be entered. When inside this context
manager, the engine can be accessed with BaseSQLDB.engine.
Upon entering, the DB class can then be used as an asynchronous context
manager to enter transactions. If an exception is raised the transaction is
rolled back automatically. If the inner context exits peacefully, the
transaction is committed automatically. When inside this context manager,
the DB connection can be accessed with BaseSQLDB.conn.
For example:
db_name = ...
url = BaseSQLDB.available_urls()[db_name]
MyDBClass = BaseSQLDB.available_implementations(db_name)[0]
db = MyDBClass(url)
async with db.engine_context():
async with db:
# Do something in the first transaction
# Commit will be called automatically
async with db:
# This transaction will be rolled back due to the exception
raise Exception(...)
Source code in diracx-db/src/diracx/db/sql/utils/base.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
Attributes
metadata
instance-attribute
engine
property
The engine to use for database operations.
It is normally not necessary to use the engine directly, unless you are doing something special, like writing a test fixture that gives you a db.
Requires that the engine_context has been entered.
conn
property
Functions
available_implementations(db_name)
classmethod
Return the available implementations of the DB in reverse priority order.
Source code in diracx-db/src/diracx/db/sql/utils/base.py
available_urls()
classmethod
Return a dict of available database urls.
The list of available URLs is determined by environment variables
prefixed with DIRACX_DB_URL_{DB_NAME}.
Source code in diracx-db/src/diracx/db/sql/utils/base.py
post_create(conn)
async
classmethod
transaction()
classmethod
engine_context()
async
Context manage to manage the engine lifecycle.
This is called once at the application startup (see lifetime_functions).
Source code in diracx-db/src/diracx/db/sql/utils/base.py
ping()
async
Check whether the connection to the DB is still working.
We could enable the pre_ping in the engine, but this would be ran at
every query.
Source code in diracx-db/src/diracx/db/sql/utils/base.py
Functions
find_time_resolution(value)
Source code in diracx-db/src/diracx/db/sql/utils/base.py
apply_search_filters(column_mapping, stmt, search)
Source code in diracx-db/src/diracx/db/sql/utils/base.py
apply_sort_constraints(column_mapping, stmt, sorts)
Source code in diracx-db/src/diracx/db/sql/utils/base.py
uuid7_to_datetime(uuid)
Convert a UUIDv7 to a datetime.
Source code in diracx-db/src/diracx/db/sql/utils/base.py
uuid7_from_datetime(dt, *, randomize=True)
Generate a UUIDv7 corresponding to the given datetime.
If randomize is True, the standard uuid7 function is used resulting in the lowest 62-bits being random. If randomize is False, the UUIDv7 will be the lowest possible UUIDv7 for the given datetime.
Source code in diracx-db/src/diracx/db/sql/utils/base.py
Functions
functions
Classes
utcnow
Bases: FunctionElement
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
Attributes
type = DateTime()
class-attribute
instance-attribute
inherit_cache = True
class-attribute
instance-attribute
date_trunc
Bases: FunctionElement
Sqlalchemy function to truncate a date to a given resolution.
Primarily used to be able to query for a specific resolution of a date e.g.
select * from table where date_trunc('day', date_column) = '2021-01-01'
select * from table where date_trunc('year', date_column) = '2021'
select * from table where date_trunc('minute', date_column) = '2021-01-01 12:00'
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
Attributes
type = DateTime()
class-attribute
instance-attribute
inherit_cache = False
class-attribute
instance-attribute
days_since
Bases: FunctionElement
Sqlalchemy function to get the number of days since a given date.
Primarily used to be able to query for a specific resolution of a date e.g.
select * from table where days_since(date_column) = 0
select * from table where days_since(date_column) = 1
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
Attributes
type = DateTime()
class-attribute
instance-attribute
inherit_cache = False
class-attribute
instance-attribute
Functions
pg_utcnow(element, compiler, **kw)
ms_utcnow(element, compiler, **kw)
mysql_utcnow(element, compiler, **kw)
sqlite_utcnow(element, compiler, **kw)
pg_date_trunc(element, compiler, **kw)
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
mysql_date_trunc(element, compiler, **kw)
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
sqlite_date_trunc(element, compiler, **kw)
Source code in diracx-db/src/diracx/db/sql/utils/functions.py
pg_days_since(element, compiler, **kw)
mysql_days_since(element, compiler, **kw)
sqlite_days_since(element, compiler, **kw)
substract_date(**kwargs)
Types
types
Attributes
Column = partial(RawColumn, nullable=False)
module-attribute
NullColumn = partial(RawColumn, nullable=True)
module-attribute
DateNowColumn = partial(Column, type_=(DateTime(timezone=True)), server_default=(utcnow()))
module-attribute
Classes
EnumBackedBool
Bases: TypeDecorator
Maps a EnumBackedBool() column to True/False in Python.
Source code in diracx-db/src/diracx/db/sql/utils/types.py
Attributes
impl = types.Enum('True', 'False', name='enum_backed_bool')
class-attribute
instance-attribute
cache_ok = True
class-attribute
instance-attribute
Functions
process_bind_param(value, dialect)
SmarterDateTime
Bases: TypeDecorator
A DateTime type that also accepts ISO8601 strings.
Takes into account converting timezone aware datetime objects into naive form and back when needed.
Source code in diracx-db/src/diracx/db/sql/utils/types.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |