Merge pull request #931 from elventear/postgresql_db

Allow change of ownership and checks for existing database
pull/922/merge
Michael DeHaan 12 years ago
commit b3b607ff5e

@ -27,26 +27,45 @@ else:
# PostgreSQL module specific support methods. # PostgreSQL module specific support methods.
# #
def set_owner(cursor, db, owner):
query = "ALTER DATABASE %s OWNER TO %s" % (db, owner)
cursor.execute(query)
return True
def db_owned_by(cursor, db, user):
query = """SELECT * FROM pg_database JOIN pg_user ON datdba = usesysid
WHERE usename = %(user)s and datname = %(db)s"""
cursor.execute(query, {'db':db, 'user':user})
return cursor.rowcount == 1
def db_exists(cursor, db): def db_exists(cursor, db):
query = "SELECT * FROM pg_database WHERE datname=%(db)s" query = "SELECT * FROM pg_database WHERE datname=%(db)s"
cursor.execute(query, {'db': db}) cursor.execute(query, {'db': db})
return cursor.rowcount == 1 return cursor.rowcount == 1
def db_delete(cursor, db): def db_delete(cursor, db):
query = "DROP DATABASE %s" % db if db_exists(cursor, db):
cursor.execute(query) query = "DROP DATABASE %s" % db
return True cursor.execute(query)
return True
else:
return False
def db_create(cursor, db, owner, template, encoding): def db_create(cursor, db, owner, template, encoding):
if owner: if not db_exists(cursor, db):
owner = " OWNER %s" % owner if owner:
if template: owner = " OWNER %s" % owner
template = " TEMPLATE %s" % template if template:
if encoding: template = " TEMPLATE %s" % template
encoding = " ENCODING '%s'" % encoding if encoding:
query = "CREATE DATABASE %s%s%s%s" % (db, owner, template, encoding) encoding = " ENCODING '%s'" % encoding
cursor.execute(query) query = "CREATE DATABASE %s%s%s%s" % (db, owner, template, encoding)
return True cursor.execute(query)
return True
elif owner and not db_owned_by(cursor, db, owner):
return set_owner(cursor, db, owner)
else:
return False
# =========================================== # ===========================================
# Module execution. # Module execution.
@ -100,12 +119,10 @@ def main():
module.fail_json(msg="unable to connect to database: %s" % e) module.fail_json(msg="unable to connect to database: %s" % e)
try: try:
if db_exists(cursor, db): if state == "absent":
if state == "absent": changed = db_delete(cursor, db)
changed = db_delete(cursor, db) elif state == "present":
else: changed = db_create(cursor, db, owner, template, encoding)
if state == "present":
changed = db_create(cursor, db, owner, template, encoding)
except Exception, e: except Exception, e:
module.fail_json(msg="Database query failed: %s" % e) module.fail_json(msg="Database query failed: %s" % e)

Loading…
Cancel
Save