# Path: postgraas_server/backends/exceptions.py
# class PostgraasApiException(Exception):
#     """Base exception which should be used by backends instead of their own
#     backend specific exceptions.
# 
#     .. example::
# 
#         try:
#             docker_backend.do_something()
#         except docker.errors.APIError as e:
#             raise PostgraasApiException(str(e))
# 
#     """
# 
#     def __init__(self, message=None):
#         self.message = message
# 
#     def __str__(self):
#         return self.message


import datetime
import logging
import psycopg2
from flask import current_app
from flask_restful import fields, Resource, marshal_with, reqparse, abort
from flask_sqlalchemy import SQLAlchemy
from postgraas_server.backends.exceptions import PostgraasApiException
from contextlib import closing
            with closing(psycopg2.connect(
                    user=entity.username,
                    password=args['db_pwd'],
                    host=current_app.postgraas_backend.master_hostname,
                    port=entity.port,
                    dbname=entity.db_name
            )) as conn:
                cur = conn.cursor()
                cur.execute("select count(pid) from pg_stat_activity where datname = %s ;", (entity.db_name,))
                other_sessions = cur.fetchone()[0]-1
        except Exception as ex:
            return_code = 401 if 'authentication failed' in str(ex) else 500
            abort(return_code, status='failed', msg='Could not connect to postgres instance: {}'.format(str(ex)))

        if other_sessions > 0:
            abort(409, status='failed', msg='Database contains other {} active sessions. Please close or terminate all sessions before deleting'.format(other_sessions))

        if not current_app.postgraas_backend.exists(entity):
            logger.warning(
                "container {} does not exist, how could that happen?".format(entity.container_id)
            )
            db.session.delete(entity)
            db.session.commit()
            return {
                'status': 'success',
                'msg': 'deleted postgraas instance, but container was not found...'
            }

        try:
            current_app.postgraas_backend.delete(entity)

# Path: postgraas_server/backends/exceptions.py
# class PostgraasApiException(Exception):
#     """Base exception which should be used by backends instead of their own
#     backend specific exceptions.
# 
#     .. example::
# 
#         try:
#             docker_backend.do_something()
#         except docker.errors.APIError as e:
#             raise PostgraasApiException(str(e))
# 
#     """
# 
#     def __init__(self, message=None):
#         self.message = message
# 
#     def __str__(self):
#         return self.message


# Path: postgraas_server/management_resources.py
import datetime
import logging
import psycopg2
from flask import current_app
from flask_restful import fields, Resource, marshal_with, reqparse, abort
from flask_sqlalchemy import SQLAlchemy
from postgraas_server.backends.exceptions import PostgraasApiException
from contextlib import closing

            with closing(psycopg2.connect(
                    user=entity.username,
                    password=args['db_pwd'],
                    host=current_app.postgraas_backend.master_hostname,
                    port=entity.port,
                    dbname=entity.db_name
            )) as conn:
                cur = conn.cursor()
                cur.execute("select count(pid) from pg_stat_activity where datname = %s ;", (entity.db_name,))
                other_sessions = cur.fetchone()[0]-1
        except Exception as ex:
            return_code = 401 if 'authentication failed' in str(ex) else 500
            abort(return_code, status='failed', msg='Could not connect to postgres instance: {}'.format(str(ex)))

        if other_sessions > 0:
            abort(409, status='failed', msg='Database contains other {} active sessions. Please close or terminate all sessions before deleting'.format(other_sessions))

        if not current_app.postgraas_backend.exists(entity):
            logger.warning(
                "container {} does not exist, how could that happen?".format(entity.container_id)
            )
            db.session.delete(entity)
            db.session.commit()
            return {
                'status': 'success',
                'msg': 'deleted postgraas instance, but container was not found...'
            }

        try:
            current_app.postgraas_backend.delete(entity)

        except PostgraasApiException as e: