pythonpostgresqlsqlitepsycopg2python-db-api

Python Psycopg executescript method


the Python db-api implementation for sqlite has a convinient method executescript() to execute multi-statement SQL scripts. It is very useful for instance for db creation. See sqlite driver documentation.

I can't find a similar one for Psycopg db-api driver for PostgreSQL. Does executescript() exist in Psycopg? Any alternative?

Thanks


Solution

  • You don't need it -- a single query string can already contain multiple separate queries.

    Quoting from the wire protocol documentation, emphasis added:

    A simple query cycle is initiated by the frontend sending a Query message to the backend. The message includes an SQL command (or commands) expressed as a text string. The backend then sends one or more response messages depending on the contents of the query command string, and finally a ReadyForQuery response message. ReadyForQuery informs the frontend that it can safely send a new command. (It is not actually necessary for the frontend to wait for ReadyForQuery before issuing another command, but the frontend must then take responsibility for figuring out what happens if the earlier command fails and already-issued later commands succeed.)

    ...and later:

    Since a query string could contain several queries (separated by semicolons), there might be several such response sequences before the backend finishes processing the query string. ReadyForQuery is issued when the entire string has been processed and the backend is ready to accept a new query string.


    Thus, the standard cursor.execute() call can be given a semicolon-separated list of individual queries to run.