def disconnect_database():
    try:
        # Is package installed
        pkg_resources.get_distribution('psycopg2')  # noqa
    except pkg_resources.DistributionNotFound:
        return

    if not hasattr(cherrypy.thread_data,
                   'dbconn') or cherrypy.thread_data.dbconn is None:
        # There is already no connection
        return
    else:
        conn = cherrypy.thread_data.dbconn
        sql = LibPool().libsql
        if conn.autocommit is False:
            # Rollback transaction mode, need to be done before disconnect
            sql.finish_trans_mode(action='rollback')

        # On the end of request, putconn back to Pool
        sql.disconnect()
def rollback_trans_mode():
    try:
        # Is package installed
        pkg_resources.get_distribution('psycopg2')  # noqa
    except pkg_resources.DistributionNotFound:
        return

    if not hasattr(cherrypy.thread_data,
                   'dbconn') or cherrypy.thread_data.dbconn is None:
        # Do not rollback transaction without connection
        return
    else:
        conn = cherrypy.thread_data.dbconn
        if conn.autocommit is not False:
            # Do not rollback transaction without transaction mode, putconn back to Pool
            sql = LibPool().libsql
            sql.disconnect()
            return

    # If exception is raised during handling a request, rolllback transaction
    sql = LibPool().libsql
    sql.finish_trans_mode(action='rollback')
    sql.disconnect()