Using Python & Peewee, I want to create a function that takes a SQL view name as an argument and returns its results. To avoid any unwanted SQL injections, I want to pass the view name as the SQL query parameter:
def run_view_query(view_name: str):
query = BaseModel.raw("SELECT * FROM %s", view_name)
return query
The problem is that Peewee automatically adds apostrophes around the keyword, so I'm getting the following error:
peewee.ProgrammingError: syntax error at or near "'vw_all_users'"
LINE 1: SELECT * FROM 'vw_all_users'
I know I can do it using python f-string like this:
query = BaseModel.raw(f"SELECT * FROM {view_name}")
but then I'd have to do some regex validation for the possible threat of SQL injections. Is there any better solution for that?