I'm writing a REST to SQL server in Python and am trying to add an additional WHERE condition to all SQL queries that I receive. For example, let's say I want to filter all queries for values of b > 4. I would do the following:
Given a SQL query that contains a WHERE clause:
SELECT * FROM my_table WHERE a < 5
becomes
SELECT * FROM my_table WHERE a < 5 AND b > 4
Given a SQL query that contains no WHERE clause:
SELECT * FROM my_table
becomes
SELECT * FROM my_table WHERE b > 4
Given a SQL query that contains a GROUP BY and no WHERE clause:
SELECT id FROM my_table GROUP BY id
becomes
SELECT id FROM my_table WHERE b > 4 GROUP BY id
I also need to handle queries that contain many combinations of other clauses, such as LIMIT, HAVING, etc.
Is there a clean way in SQL to handle a substitution like this for all queries? Or do I simply have to use regexes and pattern matching in Python to achieve this?
There is no generic existing solution to your problem. The examples you've provided cover part of the possible space of queries, but SQL allows for far more complicated queries that might need different solutions still (JOINs, UNIONs, etc.). A generic solution that would cover all possible queries would be very complicated, if possible at all.
If you know the examples you're giving cover the entire need for your specific use case, then yes - using regex and pattern matching is probably a good approach. I would recommend encapsulating your solution in a class that holds your query and exposes operations that allow you to add conditions and perform similar operations if you need them. 
That way, you can easily extend it later without affecting the use of the class in the rest of your code.
How to add an additional WHERE clause to any generic SQL query