Implemented alembic migrations, added cursors closing task.
This commit is contained in:
79
utils/mysql_scripts.py
Normal file
79
utils/mysql_scripts.py
Normal file
@@ -0,0 +1,79 @@
|
||||
|
||||
from data.schemas import SelectQueryBase
|
||||
|
||||
def build_sql_query_text(query: SelectQueryBase) -> tuple[str, list]:
|
||||
"""
|
||||
Builds a SQL query text and parameters from a SelectQuery schema object.
|
||||
|
||||
Args:
|
||||
query (SelectQuery): The query schema object.
|
||||
|
||||
Returns:
|
||||
tuple[str, list]: The SQL query text and a list of parameters.
|
||||
"""
|
||||
|
||||
# Build SELECT clause
|
||||
if query.columns == "*":
|
||||
select_clause = "SELECT *"
|
||||
else:
|
||||
select_clause = f"SELECT {', '.join(query.columns)}"
|
||||
|
||||
# Build FROM clause
|
||||
from_clause = f"FROM {query.table_name}"
|
||||
|
||||
# Build WHERE clause
|
||||
where_clause = ""
|
||||
params = []
|
||||
if query.filters:
|
||||
conditions = []
|
||||
for filter in query.filters:
|
||||
column = filter.column
|
||||
operator = filter.operator.value
|
||||
value = filter.value
|
||||
|
||||
if operator in ["IS NULL", "IS NOT NULL"]:
|
||||
conditions.append(f"{column} {operator}")
|
||||
elif operator == "IN":
|
||||
placeholders = ", ".join(["%s"] * len(value))
|
||||
conditions.append(f"{column} IN ({placeholders})")
|
||||
params.extend(value)
|
||||
else:
|
||||
# operators like < > == !=
|
||||
conditions.append(f"{column} {operator} %s")
|
||||
params.append(value)
|
||||
|
||||
where_clause = "WHERE " + " AND ".join(conditions)
|
||||
|
||||
# Build ORDER BY clause
|
||||
order_by_clause = ""
|
||||
if query.sort_by:
|
||||
order_by = []
|
||||
for sort in query.sort_by:
|
||||
column = sort.column
|
||||
order = sort.order.value
|
||||
order_by.append(f"{column} {order}")
|
||||
order_by_clause = "ORDER BY " + ", ".join(order_by)
|
||||
|
||||
# Build LIMIT and OFFSET clauses
|
||||
limit_clause = ""
|
||||
if query.limit:
|
||||
limit_clause = f"LIMIT {query.limit}"
|
||||
|
||||
offset_clause = ""
|
||||
if query.offset:
|
||||
offset_clause = f"OFFSET {query.offset}"
|
||||
|
||||
# Combine all clauses
|
||||
sql_query = """
|
||||
""".join(
|
||||
[
|
||||
select_clause,
|
||||
from_clause,
|
||||
where_clause,
|
||||
order_by_clause,
|
||||
limit_clause,
|
||||
offset_clause,
|
||||
]
|
||||
).strip()
|
||||
|
||||
return sql_query, params
|
||||
Reference in New Issue
Block a user