PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/postgresql8/cmdtools/PostgresqlRestoreDB.py

https://bitbucket.org/despiegk/postgresql8_extension
Python | 128 lines | 70 code | 5 blank | 53 comment | 3 complexity | 4c770246a78f0007ae26e3cf11c13d0b MD5 | raw file
  1. # <License type="Sun Cloud BSD" version="2.2">
  2. #
  3. # Copyright (c) 2005-2009, Sun Microsystems, Inc.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or
  7. # without modification, are permitted provided that the following
  8. # conditions are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. #
  13. # 2. Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in
  15. # the documentation and/or other materials provided with the
  16. # distribution.
  17. #
  18. # 3. Neither the name Sun Microsystems, Inc. nor the names of other
  19. # contributors may be used to endorse or promote products derived
  20. # from this software without specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY SUN MICROSYSTEMS, INC. "AS IS" AND ANY
  23. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  24. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  25. # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS, INC. OR
  26. # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  27. # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  28. # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  29. # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  30. # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #
  34. # </License>
  35. from pymonkey import q
  36. from pymonkey.baseclasses.CommandWrapper import CommandWrapper
  37. import os
  38. import pwd
  39. class PostgresqlRestoreDB(CommandWrapper):
  40. """
  41. PostgreSQL Database restore utility
  42. """
  43. def __call__(self, dbname, inputfile, runAs=None,cleanDB=False,createDB=False,userName=None, dataOnly=False, format='c', schemas=[],tables=[],withACL=True,singleTransaction=True):
  44. """
  45. Restores a database
  46. @param dbname: name of the database to delete
  47. @param inputfile: name of the database to delete
  48. @param runAs: run this command as
  49. @param cleanDB: delete objects in database before restoring
  50. @param createDB: create the database. Please note that the name of the database that is created is the name specified in the dumpfile. You need to specify another database name (ex: template1) in order to connect to the database and create restore the database
  51. @param dataOnly: only restore the data
  52. @param schemas: restrict restore to schemas specified here
  53. @param tables: restrict restore to tables specified here
  54. @param honour ACLs specified in dumpfile
  55. @param singleTransaction: handle this restore in a single transaction (either everything works either everything fails) This parameter is discarded if createDB == True
  56. """
  57. def setIfTrue(fl,val,default):
  58. if val == default: return ''
  59. if val:
  60. return fl
  61. return ''
  62. def setIfFalse(fl,val,default):
  63. if val == default: return ''
  64. if not val:
  65. return fl
  66. return ''
  67. def expandList(fl,val,default):
  68. if val == default: return ''
  69. if isinstance(val,list):
  70. rc=''
  71. for i in val:
  72. rc = rc + fl + ' ' + i + ' '
  73. return rc
  74. return '%s %s' %(fl,val)
  75. def setIfNotDefault(fl,val,default):
  76. if val==default: return ''
  77. return '%s %s' %(fl,val)
  78. def noop(fl,val,default):
  79. return ''
  80. # Solve some incompatibilities
  81. if createDB and singleTransaction:
  82. q.eventhandler.raiseError('createDB = True and singleTransaction = True are mutually exclusive options')
  83. else:
  84. l_singleTransaction = singleTransaction
  85. if dbname == 'template1' and not createDB:
  86. q.eventhandler.raiseError('You cannot restore to template1. Did you forget to specify createDB=True ?')
  87. if not runAs:
  88. q.eventhandler.raiseError('Please specify a user to run this command as !')
  89. if format not in ['c','t']:
  90. q.eventhandler.raiseError('Format %s not supported by this command' %format)
  91. # Transform input to pg_restore: list of [evaluatorfunction,parametertouse, pg_restore default, flag_to_use]
  92. options_to_check = [[setIfTrue,cleanDB,False,'-c'],[setIfTrue,createDB,False,'--create'],[setIfNotDefault,format,'p','-F'],[expandList,schemas,[],'-n'],[expandList,tables,[],'-t'],[setIfFalse,withACL,True,'-x'],[setIfNotDefault,userName,None,'-U'],[setIfTrue,l_singleTransaction,False,'-1']]
  93. options = [ i[0](i[3],i[1],i[2]) for i in options_to_check]
  94. optionstring = ' '.join([o.strip() for o in options if o])
  95. binDir = q.system.fs.joinPaths(q.dirs.baseDir, "apps", "postgresql","bin")
  96. restoreCommand = "pg_restore %s -d %s %s" %(optionstring,dbname,inputfile)
  97. restoreCommandPath = q.system.fs.joinPaths(binDir,restoreCommand)
  98. #q.console.echo(restoreCommandPath)
  99. if q.platform.isWindows():
  100. exitCode, output = q.system.process.execute(restoreCommandPath, dieOnNonZeroExitCode=False)
  101. else:
  102. if runAs:
  103. exitCode, output = q.system.unix.executeAsUser(restoreCommandPath, runAs, dieOnNonZeroExitCode = False)
  104. else:
  105. exitCode, output = q.system.process.execute(restoreCommandPath, dieOnNonZeroExitCode = False)
  106. #what if exitCode is None
  107. if exitCode:
  108. raise Exception,'restore database failed with error: %s'%output
  109. return output