How can one dump a PostgreSQL database programmatically, inside Python (or another language, if possible) without executing shell scripts.
Is this possible with psychopg2 or SQLAlchemy or some other library?
I want to dump all contents of the database, not just the schema. I do not want to dump the contents of just a query.
Currently I am using
pg_dump -h localhost -U user -d db > db_dump.sql,
however I would like to make use of a library to do this with python code.
The solutions I have already found typically resort to something along the lines of:
os.system(" pg_dump -h localhost -U user -d db > db_dump.sql ")
however this just asks the host machine to run the C implementation of pg_dump.
Similarly, I notice one can dump the contents of a query using something like:
cursor.execute(SELECT x FROM t)
f = open(db_dump.sql)
for row in cursor:
f.write("insert into t values (" + str(row) + ");")
However I want to save the contents of the entire database, not just a single query.
Can it be done with python directly?
pg_dumpcommand.pg_dumpin Python, see thread (note the mention of libpq). Another related thread.