I have a code which should do a backup of existing postgresql , but when i run the code am getting error
'pg_dump' is not recognized as an internal or external command,
i tried running command pg_dump in command prompt it shows error
pg_dump: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: role "HP-LSC" does not exist
i kept the folder path of bin and lib in environment variable, but it is still showing the same error , Can anyone help me in this please
below is the code:
import subprocess
DB_NAME = 'postgress' # your db name
DB_USER = 'postgres' # you db user
DB_HOST = "localhost"
DB_PASSWORD = 'abc'# your db password
dump_success = 1
print ('Backing up %s database ' % (DB_NAME))
command_for_dumping = f'pg_dump --host={DB_HOST} ' \
f'--dbname={DB_NAME} ' \
f'--username={DB_USER} ' \
f'--no-password ' \
f'--file=backup.dmp '
try:
proc = subprocess.Popen(command_for_dumping, shell=True, env={
'PGPASSWORD': DB_PASSWORD
})
proc.wait()
except Exception as e:
dump_success = 0
print('Exception happened during dump %s' %(e))
if dump_success:
print('db dump successfull')
print(' restoring to a new database database')
backup_file = 'tmp/backup.dmp'
"""give absolute path of your dump file. This script will create the backup.dmp in the same directory from which u are running the script """
if not dump_success:
print('dump unsucessfull. retsore not possible')
else:
try:
process = subprocess.Popen(
['pg_restore',
'--no-owner',
'--dbname=postgresql://{}:{}@{}:{}/{}'.format('postgres',#db user
'abc', #db password
'localhost', #db host
'5432', 'ReplicaDB'), #db port ,#db name
'-v',
backup_file],
stdout=subprocess.PIPE
)
output = process.communicate()[0]
except Exception as e:
print('Exception during restore %e' %(e) )
Thank you