From 3fbf64566540450e4cf6cbbd67af5b114987ca64 Mon Sep 17 00:00:00 2001 From: Jan Dittberner Date: Fri, 9 Jan 2015 19:35:37 +0100 Subject: [PATCH] implement pgsqltasks --- gvapgsql/pgsqltasks/tasks.py | 64 +++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/gvapgsql/pgsqltasks/tasks.py b/gvapgsql/pgsqltasks/tasks.py index 039b74a..e28c228 100644 --- a/gvapgsql/pgsqltasks/tasks.py +++ b/gvapgsql/pgsqltasks/tasks.py @@ -5,6 +5,23 @@ This module defines Celery_ tasks to manage PostgreSQL users and databases. from __future__ import absolute_import from celery import shared_task +from celery.utils.log import get_task_logger + +from gvapgsql import settings +from psycopg2 import connect + + +_LOGGER = get_task_logger(__name__) + + +def _get_connection(): + return connect( + host=settings.GVAPGSQL_DBADMIN_HOST, + port=settings.GVAPGSQL_DBADMIN_PORT, + user=settings.GVAPGSQL_DBADMIN_USER, + password=settings.GVAPGSQL_DBADMIN_PASSWORD, + database='postgres', + ) @shared_task @@ -18,6 +35,15 @@ def create_pgsql_user(username, password): :rtype: str """ + with _get_connection() as conn: + with conn.cursor() as curs: + curs.execute( + """ + CREATE USER %(username)s WITH PASSWORD %(password)s + """, + {'username': username, 'password': password} + ) + @shared_task @@ -31,6 +57,14 @@ def set_pgsql_userpassword(username, password): :rtype: boolean """ + with _get_connection() as conn: + with conn.cursor() as curs: + curs.execute( + """ + ALTER ROLE %(username)s WITH PASSWORD %(password)s + """, + {'username': username, 'password': password} + ) @shared_task @@ -43,6 +77,14 @@ def delete_pgsql_user(username): :rtype: boolean """ + with _get_connection() as conn: + with conn.cursor() as curs: + curs.execute( + """ + DROP ROLE %(username)s + """, + {'username': username} + ) @shared_task @@ -56,17 +98,31 @@ def create_pgsql_database(dbname, username): :rtype: str """ + with _get_connection() as conn: + with conn.cursor() as curs: + curs.execute( + """ + CREATE DATABASE %(dbname)s OWNER %(username)s + """, + {'dbname': dbname, 'username': username} + ) @shared_task -def delete_pgsql_database(dbname, username): +def delete_pgsql_database(dbname): """ - This task deletes an existing PostgreSQL database and revokes privileges of - the given user on that database. + This task deletes an existing PostgreSQL database. :param str dbname: database name - :param str username: the user name of an existing PostgreSQL user :return: True if the database has been deleted, False otherwise :rtype: boolean """ + with _get_connection() as conn: + with conn.cursor() as curs: + curs.execute( + """ + DROP DATABASE %(dbname)s + """, + {'dbname': dbname} + )