import asyncio

from asyncio_redis import Connection
from asyncqlio.db import DatabaseInterface

from models import Guild, Prefix


async def convert():
    sql_db = DatabaseInterface(
        "postgresql://postgres:postgres@127.0.0.1:5432/lolibot")
    redis_db = await Connection.create(host="localhost", port=6379)

    await sql_db.connect()

    keys = await redis_db.keys_aslist("*:prefix")
    prefixes = [(int(k.split(":")[0]), await redis_db.get(k)) for k in keys]
    print(len(prefixes))
    async with sql_db.get_session() as s:
        q = s.insert
        q.rows(*(Guild(id=k) for k, _ in prefixes))
        q.rows(*(Prefix(guild_id=k, prefix=v) for k, v in prefixes))
        r = await q.run()

    print("Inserted rows:\n\t", "\n\t".join(map(str, r)))


loop = asyncio.get_event_loop()

loop.run_until_complete(convert())
