postrgres/psycopg: cannot insert multiple commands into a prepared statement

34 Views Asked by At

I have two postgres tables that have a relationship, but no cascading delete set. So i need to delete from the related table as well as the main table manually. I am using sqlalchemy core along with psycopg3 driver.

I have the following code:

      identifiers = ['id100', 'id200']
      sql = """
         delete from related_table where entity_id in (select f.id from main_table f where identifier in (%(id1)s));
         delete from main_table where identifier in (%(id2)s)"""        
      params = {'id1': identifiers, 'id2': identifiers}
      
      conn = self.db_engine.raw_connection() 
      cursor = conn.cursor()
      cursor.execute(text(sql), params=params)

This results in the following error:

      Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python3.11/site-packages/psycopg/cursor.py", line 732, in execute
    raise ex.with_traceback(None)
psycopg.errors.SyntaxError: cannot insert multiple commands into a prepared statement

What is the proper way of executing multiple statements without having to loop (and consequently make round trips)?

0

There are 0 best solutions below