I'm working with Odoo 13 and in a wizard (models.TransientModel) file I need to execute a PostgreSQL query to fetch some data based on the values of the fields selected by wizard view. I was to told to write the query in a way to prevent SQL Injection.This is the way I tried to handle this, but there's an error.
active_model = tools.ustr(context.get('active_model').replace('.', '_'))
self._cr.execute("""select hr_employee_id from %s where active='t' and id in %s
""", (active_model, (tuple(context.get('active_ids')),)))
Error:
psycopg2.ProgrammingError: syntax error at or near "'assignment_assignment'"
LINE 1: select hr_employee_id from 'assignment_assignment' where act...
The above code return the parameter plus an extra single quotation which breaks the query. I solved the problem using bellow code:
active_model = tools.ustr(context.get('active_model').replace('.', '_'))
self._cr.execute("select hr_employee_id from " + active_model + " where active='t' and id in %s", (tuple(context.get('active_ids')),))
But I'm not sure how much correct it is and how safe it is against SQL Injection. Therefor, I'm wonder to know how can I handle above code in a safe way to prevent SQL Injection?