postgresql_ext: cascade extension creating/deleting (#50717)

* postgresql_ext: cascade extension creating/deleting (#1)

* postgresql_ext: cascade extension creating/deleting

* Address code review feedback
This commit is contained in:
Kostiantyn Nemchenko 2019-02-02 12:22:10 +02:00 committed by ansibot
parent d043003cff
commit e81287593b

View file

@ -71,6 +71,13 @@ options:
- The database extension state
default: present
choices: [ "present", "absent" ]
cascade:
description:
- Automatically install/remove any extensions that this extension depends on
that are not already installed/removed (supported since PostgreSQL 9.6).
type: bool
default: no
version_added: '2.8'
notes:
- The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.
- This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on
@ -89,6 +96,12 @@ EXAMPLES = '''
name: postgis
db: acme
schema: extensions
# Adds earthdistance to the database "template1"
- postgresql_ext:
name: earthdistance
db: template1
cascade: true
'''
import traceback
@ -119,20 +132,24 @@ def ext_exists(cursor, ext):
return cursor.rowcount == 1
def ext_delete(cursor, ext):
def ext_delete(cursor, ext, cascade):
if ext_exists(cursor, ext):
query = "DROP EXTENSION \"%s\"" % ext
if cascade:
query += " CASCADE"
cursor.execute(query)
return True
else:
return False
def ext_create(cursor, ext, schema):
def ext_create(cursor, ext, schema, cascade):
if not ext_exists(cursor, ext):
query = 'CREATE EXTENSION "%s"' % ext
query = "CREATE EXTENSION \"%s\"" % ext
if schema:
query += ' WITH SCHEMA "%s"' % schema
query += " WITH SCHEMA \"%s\"" % schema
if cascade:
query += " CASCADE"
cursor.execute(query)
return True
else:
@ -155,6 +172,7 @@ def main():
ext=dict(required=True, aliases=['name']),
schema=dict(default=""),
state=dict(default="present", choices=["absent", "present"]),
cascade=dict(type='bool', default=False),
ssl_mode=dict(default='prefer', choices=[
'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(default=None),
@ -169,6 +187,7 @@ def main():
ext = module.params["ext"]
schema = module.params["schema"]
state = module.params["state"]
cascade = module.params["cascade"]
sslrootcert = module.params["ssl_rootcert"]
changed = False
@ -224,10 +243,10 @@ def main():
changed = ext_exists(cursor, ext)
else:
if state == "absent":
changed = ext_delete(cursor, ext)
changed = ext_delete(cursor, ext, cascade)
elif state == "present":
changed = ext_create(cursor, ext, schema)
changed = ext_create(cursor, ext, schema, cascade)
except NotSupportedError as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
except Exception as e: