From 95fc5dd4a85b649c97312348cdb8b640ad2a07e8 Mon Sep 17 00:00:00 2001 From: Pepe Barbe Date: Tue, 14 Aug 2012 15:53:18 -0500 Subject: [PATCH 1/2] Fix using postgres default values When initalizing a connection to psycopg2, in order to use the default values, the keywords must be missing. So we use a dictionary as a kwarg and include only the keywords that do not have an empty value on the module parameters. --- library/postgresql_db | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/library/postgresql_db b/library/postgresql_db index 1b894f71b1..e57ef720f4 100755 --- a/library/postgresql_db +++ b/library/postgresql_db @@ -75,11 +75,19 @@ def main(): encoding = module.params["encoding"] state = module.params["state"] changed = False + + # To use defaults values, keyword arguments must be absent, so + # check which values are empty and don't include in the **kw + # dictionary + params_map = { + "login_host":"host", + "login_user":"user", + "login_password":"password" + } + kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems() + if k in params_map and v != '' ) try: - db_connection = psycopg2.connect(host=module.params["login_host"], - user=module.params["login_user"], - password=module.params["login_password"], - database="template1") + db_connection = psycopg2.connect(database="template1", **kw) # Enable autocommit so we can create databases db_connection.autocommit = True cursor = db_connection.cursor() From 7dcd1bd223c6eb1938ce0a49fda6506c79e18e03 Mon Sep 17 00:00:00 2001 From: Pepe Barbe Date: Tue, 14 Aug 2012 15:55:47 -0500 Subject: [PATCH 2/2] Autocommit support for psycopg2 < 2.4.2 --- library/postgresql_db | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/postgresql_db b/library/postgresql_db index e57ef720f4..8bfdc9fd20 100755 --- a/library/postgresql_db +++ b/library/postgresql_db @@ -89,7 +89,12 @@ def main(): try: db_connection = psycopg2.connect(database="template1", **kw) # Enable autocommit so we can create databases - db_connection.autocommit = True + if psycopg2.__version__ >= '2.4.2': + db_connection.autocommit = True + else: + db_connection.set_isolation_level(psycopg2 + .extensions + .ISOLATION_LEVEL_AUTOCOMMIT) cursor = db_connection.cursor() except Exception, e: module.fail_json(msg="unable to connect to database: %s" % e)