import os
import logging
from contextlib import closing
from functools import wraps

import psycopg2.extras

from minerva.util.debug import log_call_basic
from minerva.db import parse_db_url, extract_safe_url


def connect():
    db_url = os.getenv("TEST_DB_URL")

    if db_url is None:
        raise Exception("Environment variable TEST_DB_URL not set")

    scheme, user, password, host, port, database = parse_db_url(db_url)

    if scheme != "postgresql":
        raise Exception("Only PostgreSQL connections are supported")

    conn = psycopg2.connect(
        database=database, user=user, password=password,
        host=host, port=port,
        connection_factory=psycopg2.extras.LoggingConnection)

    logging.info("connected to {}".format(extract_safe_url(db_url)))

    conn.initialize(logging.getLogger(""))

    conn.commit = log_call_basic(conn.commit)
    conn.rollback = log_call_basic(conn.rollback)

    return conn


def with_conn(*setup_functions):
    def dec_fn(f):
        """
        Decorator for functions that require a database connection:

        @with_conn
        def somefunction(conn):
            ...
        """
        @wraps(f)
        def wrapper(*args, **kwargs):
            with closing(connect()) as conn:
                for setup_fn in setup_functions:
                    setup_fn(conn)

                return f(conn, *args, **kwargs)

        return wrapper

    return dec_fn


def with_dataset(dataset):
    def dec_fn(f):
        @wraps(f)
        def wrapper(conn, *args, **kwargs):
            with closing(conn.cursor()) as cursor:
                d = dataset()
                d.load(cursor)

            conn.commit()

            return f(conn, d, *args, **kwargs)

        return wrapper

    return dec_fn

@@ -275,87 +275,14 @@
 _url
- is None
 :%0A    
-    raise Exception(%22Environment variable TEST_DB_URL not set%22)%0A%0A
     
@@ -350,16 +350,20 @@
 b_url)%0A%0A
+    
     if s
@@ -385,16 +385,20 @@
 resql%22:%0A
+    
         
@@ -455,24 +455,267 @@
 upported%22)%0A%0A
+        conn_msg = extract_safe_url(db_url)%0A    else:%0A        user = 'minerva_admin'%0A        password = None%0A        host = None%0A        port = None%0A        database = 'minerva'%0A%0A        conn_msg = 'local database using trust authentication'%0A%0A
     conn = p
@@ -927,32 +927,16 @@
 mat(
-extract_safe_url(db_url)
+conn_msg
 ))%0A%0A
@@ -967,21 +967,12 @@
 ing.
-getLogger(%22%22)
+root
 )%0A%0A 

Add support for default libpsql configuration to connect to database