Created Queries and Execute endpoint
This commit is contained in:
68
utils/scripts.py
Normal file
68
utils/scripts.py
Normal file
@@ -0,0 +1,68 @@
|
||||
# add_user.py
|
||||
|
||||
import asyncio, logging
|
||||
import secrets
|
||||
from sqlalchemy.future import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from getpass import getpass
|
||||
from data.db import engine, SessionLocal
|
||||
from data.models import Base, User, UserRole
|
||||
|
||||
|
||||
async def pools_creator():
|
||||
from data.crud import read_all_connections
|
||||
from dbs import mysql
|
||||
|
||||
async with SessionLocal() as db:
|
||||
connections = await read_all_connections(db=db)
|
||||
|
||||
for connection in connections:
|
||||
mysql.pools[connection.id] = await mysql.pool_creator(connection=connection)
|
||||
logging.info(msg='Created Pools')
|
||||
|
||||
async def pools_destroy():
|
||||
from dbs import mysql
|
||||
for connection_id, pool in mysql.pools.items():
|
||||
pool.close()
|
||||
await pool.wait_closed()
|
||||
logging.info(f'Closed pool: {connection_id}')
|
||||
|
||||
async def db_startup():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
def create_secret():
|
||||
return secrets.token_hex(32)
|
||||
|
||||
async def create_user():
|
||||
|
||||
async with SessionLocal() as session:
|
||||
username = input("Enter username: ").strip()
|
||||
role_input = input("Enter role (admin/user): ").strip().lower()
|
||||
print('\n')
|
||||
if role_input not in UserRole._value2member_map_:
|
||||
print("> Invalid role. Please enter 'admin' or 'user'.")
|
||||
return
|
||||
|
||||
role = UserRole(role_input)
|
||||
|
||||
# Check if username already exists
|
||||
result = await session.execute(select(User).filter_by(username=username))
|
||||
existing_user = result.scalars().first()
|
||||
if existing_user:
|
||||
print(f"> Username '{username}' is already taken.")
|
||||
return
|
||||
|
||||
# Create new user
|
||||
api_key = create_secret()
|
||||
new_user = User(username=username, role=role, api_key=api_key)
|
||||
session.add(new_user)
|
||||
await session.commit()
|
||||
await session.refresh(new_user)
|
||||
|
||||
|
||||
print(f"> User '{username}' with role '{role.value}' created successfully.")
|
||||
print(f"> API Key: {api_key}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(create_user())
|
||||
78
utils/sql_creator.py
Normal file
78
utils/sql_creator.py
Normal file
@@ -0,0 +1,78 @@
|
||||
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