In what way can I execute a psql command from a Python script? My code inserts and updates data from a PostgreSQL DB (using psycopg2 and cursor method). It works fine when I execute a query like
cursor.execute("UPDATE Segment set idcurve = %s where id = %s ", (id_curve, id_segment,))
But in the psql case, when I pass commands to cursor.execute
(see edits to similar question) I get SyntaxError: syntax error at or near "\"
.
Moreover, the command fails in console.sql DataGRIP (it executes for all the rows anyway...)
Does this command only work in the shell (do I have to use os.system)? as cursor
is not able to interpret it?
EDIT trying with subprocess:
import subprocess
sql = """SELECT uuid IS NULL AS is_uuid FROM dpoint WHERE uuid = '5547f4b7-00b3-4aac-8ceb-c9ca163a0214';
\gset
\if :is_uuid
INSERT INTO DPoint (uuid) VALUES ('5547f4b7-00b3-4aac-8ceb-c9ca163a0214');
WITH ins1 AS (INSERT INTO Point (latitude, longitude, srid)
VALUES (64.44, 28.77, 4326) RETURNING id AS id_point)
INSERT INTO SPoint (idPoint, uuiddpt) VALUES ((SELECT id_point FROM ins1), '5547f4b7-00b3-4aac-8ceb-c9ca163a0214');
\endif
"""
subprocess.check_call(['psql -h localhost -d dbase -U myuser -W --command={}'.format(sql)], env={'PGPASSWORD': 'mypass'})
Throws OSError: [Errno 36] File name too long
EDIT2
subprocess.check_call(['psql', '-q', '-U', 'myuser', '-h', 'localhost', '-c', '{}'.format(sql), 'dbase'], env={'PGPASSWORD': 'mypass'})
When I split up all the arguments the query is trying to execute -> it fails with syntax error at or near "\"
. -E
(as Lu M suggests) does not help. It works in the case where I save my query to .sql file however I would like to execute it interactively.
EDIT3
According to psql tutorial in chapter --command=command there are two options available to mix SQL and psql meta-commands. In what way is it possible to wrap it in a subprocess? I tried both, but undesired extra backslashes appear and it is not recognized as one command:
subprocess.check_call(['psql', '-q', '-U', 'myuser', '-h', 'localhost',
'-c', '{}'.format(sql),
'-c', '{}'.format('\gset'),
'-c', '{}'.format('\if :is_uuid '),
'-c', '{}'.format(sql2),
'-c', '{}'.format('\endif'), 'dbase'],
env={'PGPASSWORD': 'mypass'})
fails with unrecognized value ":is_uuid" for "\if expression": Boolean expected