import pymysql
import pymysql.cursors

from flyers.database import DatabaseConf
from flyers.logs import logger


def execute(conn: pymysql.Connection, consumer_func, auto_commit=True):
    with conn.cursor() as cursor:
        consumer_func(cursor)
        if auto_commit:
            conn.commit()


def create_connection(conf: DatabaseConf) -> pymysql.Connection:
    try:
        return pymysql.connect(host=conf.host,
                               port=conf.port,
                               user=conf.user,
                               password=conf.password,
                               database=conf.database,
                               cursorclass=pymysql.cursors.DictCursor)
    except Exception:
        msg = 'Init connection error, conf: {}'.format(conf.__dict__)
        logger.exception(msg)
        raise Exception(msg)


def show_mysql_server_version(conn: pymysql.Connection):
    with conn.cursor() as cursor:
        cursor.execute("SELECT VERSION()")
        return cursor.fetchone()
