import asyncio

import asyncpg

POOL_CFG = {"database": "db", "user": "usr", "password": "", "host": "localhost"}

pool = None


async def init_db():
    global pool
    pool = await asyncpg.create_pool(**POOL_CFG)


def with_conn(fn):
    async def inner(*args, **kwargs):
        async with pool.acquire() as conn:
            return await fn(conn, *args, **kwargs)

    return inner


def listener(conn, pid, ch, msg):
    print(f"msg: {msg} ch: {ch} pid: {pid}")


async def sub():
    conn = await asyncpg.connect(
        user="usr", password="", database="db", host="127.0.0.1"
    )
    await conn.add_listener("test", listener)


@with_conn
async def pub(conn, msg):
    print("sending", msg)
    await conn.execute(f"NOTIFY test, '{msg}'")


async def main():
    await init_db()
    await sub()
    await asyncio.sleep(3)
    await pub("w00t")
    await pub("one")
    await asyncio.sleep(1.0e10)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        exit()

import asyncio

import asyncpg

POOL_CFG = {"database": "db", "user": "usr", "password": "", "host": "localhost"}

pool = None


async def init_db():
    global pool
    pool = await asyncpg.create_pool(**POOL_CFG)


def with_conn(fn):
    async def inner(*args, **kwargs):
        async with pool.acquire() as conn:
            return await fn(conn, *args, **kwargs)

    return inner


def listener(conn, pid, ch, msg):
    print(f"msg: {msg} ch: {ch} pid: {pid}")


async def sub():
    conn = await asyncpg.connect(
        user="usr", password="", database="db", host="127.0.0.1"
    )
    await conn.add_listener("test", listener)


@with_conn
async def pub(conn, msg):
    print("sending", msg)
    await conn.execute(f"NOTIFY test, '{msg}'")


async def main():
    await init_db()
    await sub()
    await asyncio.sleep(3)
    await pub("w00t")
    await pub("one")
    await asyncio.sleep(1.0e10)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        exit()
