Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add asynchronous notification feature into db_postgres lib #25

Open
geohuz opened this issue Jul 22, 2024 · 0 comments
Open

Add asynchronous notification feature into db_postgres lib #25

geohuz opened this issue Jul 22, 2024 · 0 comments

Comments

@geohuz
Copy link

geohuz commented Jul 22, 2024

Summary

As stated in Postgresql official documentation: https://www.postgresql.org/docs/current/libpq-notify.html , it is missed from db_connector/postgres.

Description

As the implementaion of the code require asyncdispatch lib, I'm not sure if it is a proper way to put into the db_connector.

Alternatives

As the implement requires less than dozen line of codes, put them into any third party package seems awkward.

Examples

Here is the simple implementation of the pg's async notfication with asyncdispatch:

import asyncdispatch
import db_connector/db_postgres
import db_connector/postgres

type PGNotify = tuple [channel: string, message: string]

let conn = db_postgres.open("localhost:xxx", "postgres", "", "")
# listen to notification
conn.exec(sql(""" LISTEN "testChannel" """))

proc recvNotify(conn: DbConn): Future[PGNotify] =
  let fd = AsyncFD(pqsocket(conn))
  let retFuture = newFuture[PGNotify]()

  proc cb(fd: AsyncFD): bool {.closure, gcsafe.} =
    if not retFuture.finished:
      if pqconsumeInput(conn)==0:
        retFuture.fail(newException(ValueError, $pqerrorMessage(conn)))
      else:
        let notify = pqnotifies(conn)
        if notify != nil:
          unregister(fd) 
          retFuture.complete((channel: $notify.relname, message: $notify.extra))

    return true

  register(fd)  
  addRead(fd, cb) 
  return retFuture

proc processPgNotify() {.async.} =
  while true:
    let notify = await recvNotify(conn)
    echo "channel, message ", notify.channel, notify.message

asyncCheck processPgNotify()
runForever()

Backwards Compatibility

No response

Links

https://www.postgresql.org/docs/current/libpq-notify.html

example of official documentation(in C): https://www.postgresql.org/docs/current/libpq-example.html#LIBPQ-EXAMPLE-2

@ringabout ringabout transferred this issue from nim-lang/Nim Jul 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant