import gc
from os import environ
import tracemalloc

from mariadb import Connection


MAGIC_NUMBER = 5


host = environ.get("DB_HOST", "localhost")
port = int(environ.get("DB_PORT", "3306"))
user = environ.get("DB_USER", "root")
password = environ["DB_PASSWORD"]
database = environ.get("DB_NAME", "")


def get_connection(database_name):
    return Connection(
        host=host,
        port=port,
        user=user,
        password=password,
        database=database_name,
    )


def setup_database():
    connection = get_connection("")
    cursor = connection.cursor()
    cursor.execute(f"CREATE DATABASE IF NOT EXISTS {database}")
    connection.commit()
    connection.close()

    connection = get_connection(database)
    cursor = connection.cursor()
    query = (
        "CREATE TABLE IF NOT EXISTS a (id BIGINT PRIMARY KEY AUTO_INCREMENT, b BIGINT) "
        "ENGINE=InnoDB"
    )

    cursor.execute(query)

    cursor.execute("INSERT INTO a (b) VALUES (?)", (MAGIC_NUMBER,))
    connection.commit()
    connection.close()


def get_value():
    connection = get_connection(database)
    cursor = connection.cursor()
    cursor.execute("SELECT b FROM a WHERE b = ?", (MAGIC_NUMBER,))
    result = cursor.fetchone()
    value = result[0]
    connection.close()

    return value


if __name__ == "__main__":
    setup_database()

    tracemalloc.start()
    initial_snapshot = tracemalloc.take_snapshot()
    for _ in range(10000):
        get_value()

    gc.collect()

    final_snapshot = tracemalloc.take_snapshot()

    for allocation in final_snapshot.compare_to(initial_snapshot, "lineno"):
        print(allocation)
