"""
This folder contains very small DB functions that are reused across queries and commands
"""
from psycopg import AsyncCursor


async def table_exists(cursor: AsyncCursor, table: str):
    TABLES_EXISTS_INDEX = 0
     # autopep8: off -- it doesn't support t-strings yet
    query = t"""
        SELECT to_regclass({table:t}) IS NOT NULL AS table_exists;

    """
    # autopep8: on
    await cursor.execute(query)
    row = await cursor.fetchone()
    if row:
        return row[TABLES_EXISTS_INDEX] == 1
    else:
        return False


async def get_config_version(cursor: AsyncCursor, config_table_name: str) -> int:
     # autopep8: off -- it doesn't support t-strings yet
    query = t"SELECT version from {config_table_name:i}"
    # autopep8: on
    row = await cursor.execute(query)
    record = await row.fetchone()
    if record:
        return int(record[0])
    else:
        raise RuntimeError("No nc_db version number found in the database.")


async def get_registered_signature(cursor: AsyncCursor, class_name: str, registration_table_name: str) -> str:
     # autopep8: off -- it doesn't support t-strings yet
    query = t"SELECT signature from {registration_table_name:i} where name={class_name}"
    # autopep8: on
    row = await cursor.execute(query)
    record = await row.fetchone()
    if record:
        return str(record[0])
    else:
        raise RuntimeError("No class registration found in the database.")
