Guest User

Untitled

a guest
May 24th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import os
  2. import sys
  3. import pg
  4.  
  5. #Take the ne shcema name from the second cmd arguments (the first is the filename)
  6. newSchema = sys.argv[1]
  7. #Temp folder for the dumps
  8. dumpFile = '/test/dumps/' + str(newSchema) + '.sql'
  9. #Settings
  10. db_name = 'db_name'
  11. db_user = 'db_user'
  12. db_pass = 'db_pass'
  13. schema_as_template = 'schema_name'
  14.  
  15. #Connection
  16. pgConnect = pg.connect(dbname= db_name, host='localhost', user= db_user, passwd= db_pass)
  17. #Rename schema with the new name
  18. pgConnect.query("ALTER SCHEMA " + schema_as_template + " RENAME TO " + str(newSchema))
  19. #Dump it
  20. command = 'export PGPASSWORD="' + db_pass + '" && pg_dump -U ' + db_user + ' -n ' + str(newSchema) + ' ' + db_name + ' > ' + dumpFile
  21. os.system(command)
  22. #Rename back with its default name
  23. pgConnect.query("ALTER SCHEMA " + str(newSchema) + " RENAME TO " + schema_as_template)
  24. #Restore the previus dump to create the new schema
  25. restore = 'export PGPASSWORD="' + db_pass + '" && psql -U ' + db_user + ' -d ' + db_name + ' < ' + dumpFile
  26. os.system(restore)
  27. #Want to delete the dump file?
  28. os.remove(dumpFile)
  29. #Close connection
  30. pgConnect.close()
Add Comment
Please, Sign In to add comment