sql_utils
Sql utils are used to interact with databases.
execute_sql_queries_with_retry(db_connection_engine, queries, bulk_commit)
Executes a list of SQL queries with optional bulk commit and retry logic.
Connects to the database using the provided SQLAlchemy engine and executes each
query in the given list. If bulk_commit is True, all queries are committed
together after execution; otherwise, each query is committed individually.
Retries up to 3 times with a 2-second wait between attempts in case of
transient OperationalErrors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_connection_engine
|
Engine
|
The SQLAlchemy engine used to connect to the database. |
required |
queries
|
List[str]
|
A list of SQL queries to execute. |
required |
bulk_commit
|
bool
|
Whether to commit all queries in a single transaction. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of rows affected by the last executed query. |
Raises:
| Type | Description |
|---|---|
OperationalError
|
If the connection or query execution fails after retries. |
Example
from physical_operations_utils.sql_utils import execute_sql_queries_with_retry
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
engine = get_db_connection(f"common_trading_data_{environment}").engine
queries = [
"UPDATE my_table SET value = 1 WHERE id = 10",
"DELETE FROM my_table WHERE value IS NULL"
]
rowcount = execute_sql_queries_with_retry(engine, queries, bulk_commit=True)
print(f"{rowcount} rows affected by the last query.")
Source code in physical_operations_utils/sql_utils.py
35 36 37 38 39 40 41 42 43 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 | |
get_existing_table_names(db_connection_engine)
Retrieves the names of all existing base tables from a database.
Connects to the database using the provided SQLAlchemy engine and queries the
INFORMATION_SCHEMA.TABLES view to get the names of all base tables. Retries up
to 3 times with a 2-second wait between attempts in case of transient OperationalErrors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_connection_engine
|
Engine
|
The SQLAlchemy engine used to connect to the database. |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of base table names present in the database. |
Raises:
| Type | Description |
|---|---|
OperationalError
|
If the connection or query fails after retries. |
Example
from physical_operations_utils.sql_utils import get_existing_table_names
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
engine = get_db_connection(f"common_trading_data_{environment}").engine
table_names = get_existing_table_names(engine)
print(table_names)
Source code in physical_operations_utils/sql_utils.py
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 | |
get_latest_task_execution_time_utc(platform_conn_engine, application_name, job_id)
Retrieves the last successful execution timestamp of a task from the platform task execution tracking table.
The function queries the core_last_successful_task_execution table for a specific application and job ID and
returns the timestamp of the last successful execution in UTC. If no execution is found, it returns None.
If more than one row is returned by the query, a ValueError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
platform_conn_engine
|
Engine
|
SQLAlchemy engine to the platform database. |
required |
application_name
|
str
|
Name of the application that executed the task. |
required |
job_id
|
str
|
Identifier for the specific job/task. |
required |
Returns:
| Type | Description |
|---|---|
datetime | None
|
datetime.datetime | None: The UTC datetime of the last successful execution, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If more than one row is returned by the query. |
Exception
|
If the database connection or query fails after retries. |
Example
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
from physical_operations_utils.environment_utils import setup_environment
from physical_operations_utils.sql_utils import get_latest_task_execution_time_utc
environment = setup_environment()
engine = get_db_connection(f"physical_trading_platorm_django_{environment}")
last_run = get_latest_task_execution_time_utc(engine, "my_app", "my_task")
if last_run:
print(f"Last successful execution: {last_run}")
else:
print("No previous execution found.")
Source code in physical_operations_utils/sql_utils.py
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 | |
load_data_with_caching(db_engine, table_name, query, params, force_reload)
Loads data from a database with caching support.
If caching is enabled and the table has been previously loaded, it returns the cached DataFrame. Otherwise, it fetches the data from the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_engine
|
Engine
|
The database engine. |
required |
table_name
|
str
|
The name of the table being queried. |
required |
query
|
str
|
The SQL query to execute. |
required |
params
|
dict
|
Query parameters. |
required |
force_reload
|
bool
|
If True, forces data reloading instead of using cache. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: A pandas DataFrame containing the query results. |
Example
from physical_operations_utils.sql_utils import load_data_with_caching
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
conn = get_db_connection(f"common_trading_data_{environment}")
query = "SELECT * FROM my_table WHERE date = :date"
params = {"date": "2024-02-01"}
df = load_data_with_caching(conn.engine, "my_table", query, params, force_reload=False)
print(df.head())
Source code in physical_operations_utils/sql_utils.py
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 | |
log_task_execution(platform_conn_engine, application_name, job_id, comment=None)
Record the last successful execution timestamp (and optional comment) of a scheduled task
into the core_last_successful_task_execution table.
This function builds a single-row pandas DataFrame containing:
- application_name and job_id to identify the task,
- an optional free-text comment,
- last_successful_execution set to the current Stockholm time (with timezone).
It then upserts that row into SQL Server using upsert_into_mssql, matching on
(application_name, job_id).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
platform_conn_engine
|
Engine
|
SQLAlchemy Engine connected to the platform database. |
required |
application_name
|
str
|
The name of the application or schema (e.g. "nomination"). |
required |
job_id
|
str
|
A unique identifier for the task (e.g. "monitor variable checker"). |
required |
comment
|
str | None
|
An optional note or comment about this execution. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
OperationalError
|
If the upsert fails at the database level and is not recoverable. |
ValueError
|
If the DataFrame or key columns are malformed. |
Example
log_task_execution(
platform_conn_engine=engine,
application_name="nomination",
job_id="monitor variable checker",
comment="Ran via cron every 5 minutes"
)
Source code in physical_operations_utils/sql_utils.py
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | |
pandas_read_sql_with_retry(db_engine, query, params=None)
Executes an SQL query with automatic retry on operational failures making 5 attempts with 2 seconds wait between attempts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_engine
|
Engine
|
A SQLAlchemy database Engine instance. |
required |
query
|
str
|
The SQL query to execute. |
required |
params
|
dict
|
Dictionary of query parameters. |
None
|
Returns:; pd.DataFrame: A pandas DataFrame containing the query result.
Raises:
| Type | Description |
|---|---|
OperationalError
|
There is an error in the SQL statement. |
Example
from physical_operations_utils.sql_utils import pandas_read_sql_with_retry
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
ctd_conn = get_db_connection(f"common_trading_data_{environment}")
params={"variable_id": "SE3", "resolution_seconds": 900}
query = "SELECT * FROM my_table WHERE variable_id = :variable_id AND resolution_seconds = :resolution_seconds"
df = pandas_read_sql_with_retry(ctd_conn.engine, query, params)
print(df.head())
Source code in physical_operations_utils/sql_utils.py
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 | |
upsert_into_mssql(db_connection_engine, df, table_name, column_names, key_columns)
Performs an upsert (merge) of a pandas DataFrame into a Microsoft SQL Server table with automatic retries (5 retries with 2 second wait).
This function takes a DataFrame and attempts to insert or update rows in the specified table based on the provided key columns. The SQL query is constructed using parameterized bindings to prevent SQL injection, and column and table identifiers are validated before query generation. If the DataFrame is large, it is split into chunks to prevent exceeding parameter or query limits. The chunk size depends on the number of columns. A single transaction is used for all chunks to ensure atomicity, and operational failures are retried up to 5 times with a fixed delay between attempts.
The function returns the total number of rows affected across all chunks, as reported by the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_connection_engine
|
Engine
|
A SQLAlchemy Engine object as contained in AzureSqlConnection objects. |
required |
df
|
DataFrame
|
The pandas DataFrame containing data to upsert. |
required |
table_name
|
str
|
The name of the target SQL Server table. |
required |
column_names
|
list
|
List of column names to be inserted or updated. |
required |
key_columns
|
list
|
List of column names used to determine matches (i.e., primary or unique keys). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The total number of rows affected by the upsert operation. |
Raises:
| Type | Description |
|---|---|
OperationalError
|
Raised when an error occurs during SQL execution that is not recoverable after retries. |
ValueError
|
Raised when the input table or column names are invalid. |
Example
from physical_operations_utils.sql_utils import upsert_into_mssql
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
df = pd.DataFrame({"id": [1, 2], "value": ["A", "B"]})
affected = upsert_into_mssql(
db_connection=get_db_connection(f"common_trading_data_{environment}").engine,
df=df,
table_name="my_table",
column_names=["id", "value"],
key_columns=["id"]
)
print(f"{affected} rows affected.")
Source code in physical_operations_utils/sql_utils.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
write_to_application_log(platform_conn_engine, application_name, job_id, messages, print_log=False)
Writes a list of log messages to the core application log table with automatic retry on operational failures.
This function inserts one row per message into the core_application_log table in the physical_trading_platform_django database.
Each row includes the application name, job ID, log message, and a UTC timestamp. The function uses
parameterized SQL to safely insert values, and retries the entire operation up to 3 times in case of
transient operational errors.
The function returns the total number of rows successfully inserted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
platform_conn_engine
|
Engine
|
A SQLAlchemy Engine object for the platform database. |
required |
application_name
|
str
|
The name of the application writing to the log. |
required |
job_id
|
str
|
A unique identifier for the job or task writing the log. |
required |
messages
|
List[str]
|
A list of log messages to write. |
required |
print_log
|
bool
|
A flag to determine if log messages are printed using logging.warning. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The total number of rows written to the log table. |
Raises:
| Type | Description |
|---|---|
OperationalError
|
Raised when a database error occurs that is not resolved after 3 retry attempts. |
Example
from physical_operations_utils.sql_utils import upsert_into_mssql
from physical_operations_utils.azure_utils.azure_sql_connection import get_db_connection
row_count = write_to_application_log(
platform_conn_engine=get_db_connection(f"physical_trading_platform_django_{environment}").engine,
application_name="my_pipeline",
job_id="job_20250328_xyz",
messages=["Job started", "Job finished successfully"],
print_log=True,
)
print(f"{row_count} log entries inserted.")
Source code in physical_operations_utils/sql_utils.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |