Provided your SQL statement produces valid results, the scripts below should do what you are after. Unfortunately I have nothing at hand to test this, but you could try and give feedback.

I tried to comment it for convenience, basically the script carries out three steps:

obtain database connection parameters for the selected layer (should be postgres)

fill the connection parameters in the sql statement string

execute the sql statement

Note the protocol output of the script.